package com.miracle9.game.service;

import com.miracle9.game.bean.GameTypeSession;
import com.miracle9.game.bean.Pager;
import com.miracle9.game.dao.*;
import com.miracle9.game.entity.*;
import com.miracle9.game.enums.GameTypeEnums;
import com.miracle9.game.server.message.AmfMessageSend;
import com.miracle9.game.server.message.MessageSend;
import com.miracle9.game.server.message.StorageMethodEntity;
import com.miracle9.game.thread.DealCheatThread;
import com.miracle9.game.util.GameParameterAssist;
import com.miracle9.game.util.MyUtil;
import com.miracle9.game.util.SessionUtils;
import com.miracle9.game.util.UserParticipateRecord;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import wox.serial.SimpleWriter;
import wox.serial.XMLUtil;

import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.security.SecureRandom;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

@Service("userService")
public class UserService extends BaseService {

    private static Logger logger = LoggerFactory.getLogger(UserService.class);
    @Autowired
    private IncomeRankDao incomeRankDao;
    @Autowired
    private UserServiceDao userServiceDao;
    @Autowired
    private GoldSharkDeskDao goldSharkDeskDao;
    @Autowired
    private RechargeActivityServiceDao rechargeActivityServiceDao;
    @Autowired
    private SystemConfigServiceDao systemConfigServiceDao;
    @Autowired
    private DeskServiceDao deskServiceDao;
    @Autowired
    private UserMailServiceDao userMailServiceDao;
    @Autowired
    private UserShutupServiceDao userShutupServiceDao;
    @Autowired
    private AdminServiceDao adminServiceDao;
    @Autowired
    private PayLogServiceDao payLogServiceDao;
    @Autowired
    private ComputerOrderServiceDao computerOrderServiceDao;
    @Autowired
    private UserAwardServiceDao userAwardServiceDao;
    @Autowired
    private com.miracle9.game.dao.AdminLogServiceDao adminLogServiceDao;
    @Autowired
    private LevelInfoServiceDao levelInfoServiceDao;
    @Autowired
    private VersionServiceDao versionServiceDao;
    @Autowired
    private com.miracle9.game.dao.BusineServiceDao busineServiceDao;
    @Autowired
    private com.miracle9.game.dao.BusineInfoServiceDao busineInfoServiceDao;
    @Autowired
    private FishDeskServiceDao fishDeskServiceDao;
    @Autowired
    private NoticeServiceDao noticeServiceDao;
    @Autowired
    private PayApplyServiceDao payApplyServiceDao;
    @Autowired
    private CardDeskServiceDao cardDeskServiceDao;
    @Autowired
    private BusineInfoTempServiceDao busineInfoTempServiceDao;
    @Autowired
    private com.miracle9.game.dao.BusineLogServiceDao busineLogServiceDao;
    @Autowired
    private PromoterServiceDao1 promoterServiceDao1;
    @Autowired
    private com.miracle9.game.dao.BulletFishDeskServiceDao bulletFishDeskServiceDao;
    @Autowired
    private MermaidDeskServiceDao mermaidDeskServiceDao;
    @Autowired
    private PromoterAppService l;
    @Autowired
    private PromoterLogServiceDao promoterLogServiceDao;
    @Autowired
    private LackDeskServiceDao lackDeskServiceDao;
    @Autowired
    private UserWarningServiceDao userWarningServiceDao;
    @Autowired
    private UserWarningBakServiceDao userWarningBakServiceDao;
    @Autowired
    private JoyDeskServiceDao joyDeskServiceDao;
    @Autowired
    private WaterDeskServiceDao waterDeskServiceDao;
    @Autowired
    private UserActivityServiceDao userActivityServiceDao;
    @Autowired
    private com.miracle9.game.dao.ActivityInfoServiceDao activityInfoServiceDao;
    @Autowired
    private com.miracle9.game.dao.ActivityServiceDao activityServiceDao;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private UserRegistLogServiceDao userRegistLogServiceDao;
    @Autowired
    private UserRegistLogService userRegistLogService;
    @Autowired
    private RecordDeleteDeskServiceDao recordDeleteDeskServiceDao;
    @Autowired
    private ThousandFishDeskDao thousandFishDeskDao;
    @Autowired
    private FishKingDB fishKingDB;
    @Autowired
    private LiKuiFishDeskDao liKuiFishDeskDao;
    @Autowired
    private GoldenCicadaFishDeskDao goldenCicadaFishDeskDao;
    @Autowired
    private BcbmDeskDao bcbmDeskDao;
    @Autowired
    private TianGongDeskDao tianGongDeskDao;
    @Autowired
    private DragonTigerDeskDao dragonTigerDeskDao;
    @Autowired
    private GameService gameService;
    @Autowired
    private LoginRecordDao loginRecordDao;

    public User getUser(int id) {
        return (User) this.userServiceDao.getById(id);
    }

    public void publicKey(String modulus, String exponent, IoSession session) {
        session.setAttribute("attack", "false");
        Map<String, Object> arg = new HashMap<>();
        String key = MyUtil.substringLength(16);
        GameParameterAssist.bd.put(session, "qxokrfuvxxf4mobg");
        key = MyUtil.Base64EncodeToString(key, modulus, exponent);
        arg.put("key", key);
        arg.put("time", System.currentTimeMillis());
        Map<String, Object> map = new HashMap<>();
        map.put("method", "publicKey");
        map.put("args", new Object[]{arg});
        try {
            JSONObject localJSONObject = JSONObject.fromObject(map);
            String str1 = localJSONObject.toString();
            byte[] arrayOfByte1 = str1.getBytes("UTF-8");
            IoBuffer localIoBuffer1 = IoBuffer.allocate(arrayOfByte1.length + 4);
            localIoBuffer1.putInt(arrayOfByte1.length);
            localIoBuffer1.put(arrayOfByte1);
            localIoBuffer1.flip();
            session.write(localIoBuffer1);
        } catch (Exception localException1) {
            logger.error("", localException1);
            SimpleWriter w = new SimpleWriter();
            try {
                String str2 = XMLUtil.element2String(w.write(map));
                byte[] content = str2.getBytes("UTF-8");
                IoBuffer bb = IoBuffer.allocate(content.length + 4);
                bb.putInt(content.length);
                bb.put(content);
                bb.flip();
                session.write(bb);
            } catch (Exception e) {
                logger.error("", e);
            }
        }
    }

    public Map<String, Object> userLogin(String username, String password, String versionCode, IoSession session) {
        return userLogin(username, password, 0, versionCode, session);
    }

    public Map<String, Object> userLoginH5(String username, String password, String versionCode, IoSession session) {
        return userLoginH5(username, password, 0, versionCode, session);
    }

    public Map<String, Object> userLoginH5(String username, String password, int language, String versionCode, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        SystemConfig config = this.systemConfigServiceDao.q_CreateSqlFilter("from SystemConfig", new Object[0]);
        User user = this.userServiceDao.q_CreateSqlFilter("from User where username=?", new Object[]{username});
        if (config == null || user == null) {
            result.put("isLogin", Boolean.FALSE);
            result.put("messageStatus", 0);
            return result;
        }
        result.put("payMode", 0);
        result.put("accountProtectionState", 1);
        if (config.getRobotPromoter() != null && config.getRobotPromoter().equals(user.getPromoterName())) {
            result.put("updateAddress", config.getRobotUpdateAddress());
        } else {
            result.put("updateAddress", config.getUpdateAddress());
        }
        result.put("isLogin", Boolean.FALSE);
        result.put("messageStatus", -1);
        result.put("isShutup", Boolean.FALSE);
        result.put("user", null);
        if (!user.getPassword().equals(DigestUtils.md5Hex(password))) {
            result.put("isLogin", Boolean.FALSE);
            result.put("messageStatus", 0);
            return result;
        }
        if (user.getStatus() != 0) {
            result.put("isLogin", Boolean.FALSE);
            result.put("messageStatus", 1);
            return result;
        }
        if (config.getGameStatus() == 1 && user.getType() != 2) {
            result.put("isLogin", Boolean.FALSE);
            result.put("messageStatus", 2);
            return result;
        }
        if (!GameParameterAssist.ba.containsKey(user.getId())) {
            if (UserParticipateRecord.checkUserId_1(user.getId()) == 100) {
                result.put("isLogin", Boolean.FALSE);
                result.put("messageStatus", 15);
                synchronized (this) {
                    int nGameType = UserParticipateRecord.checkUserId_1(user.getId());
                    if (nGameType == 100) {
                        UserParticipateRecord.updateStatus(user.getId(), -1);
                    }
                }
                return result;
            }
        } else {
            logger.info("userId:[{}] 已经登录大厅了, 登录状态:[{}] !", user.getId(), UserParticipateRecord.checkUserId_1(user.getId()));
        }
        UserParticipateRecord.updateStatus(user.getId(), -1);
        synchronized (this) {
            /*if (isGameLogin(user.getId())) {
                quitToLogin(user.getId(), 4);
            } else {
                if (GameParameterAssist.ba.containsKey(user.getId())) {
                    IoSession lastClient = GameParameterAssist.ba.remove(user.getId());
                    Map<String, Object> ret = new HashMap<>();
                    ret.put("type", 4);
                    MessageSend.q.notifyAllOperating(new StorageMethodEntity(lastClient, "quitToLogin", new Object[]{ret}));
                    lastClient.removeAttribute("username");
                    lastClient.removeAttribute("id");
                    lastClient.setAttribute("needRemove", "true");
                }
                if ((user.getGameScore() > 0) || (user.getExpeScore() > 0)) {
                    int gameType = UserParticipateRecord.checkUserId_3(user.getId());
                    if (gameType != -3) {
                        result.put("isLogin", Boolean.FALSE);
                        result.put("messageStatus", 0);
                        //this.userServiceDao.updateStatus(user.getId(), 3);
                        GameService.gameKick(gameType, user.getId());
                        quitToLogin(user.getId(), 2);
                        //DealCheatThread.f(user.getId());
                        //再次调用主动退出，防止子游戏断线，通知不到服务器导致账号一直重复登录
                        gameService.logout(user.getId(), gameType, null);
                        return result;
                    }
                    clearingUserScore(user.getId());
                    user = (User) this.userServiceDao.getById(user.getId());
                }
                GameParameterAssist.aR.remove(user.getId());
            }*/

            if (GameParameterAssist.ba.containsKey(user.getId())) {
                IoSession lastClient = GameParameterAssist.ba.remove(user.getId());
                Map<String, Object> ret = new HashMap<>();
                ret.put("type", 4);
                MessageSend.q.notifyAllOperating(new StorageMethodEntity(lastClient, "quitToLogin", new Object[]{ret}));
                lastClient.removeAttribute("username");
                lastClient.removeAttribute("id");
                lastClient.setAttribute("needRemove", "true");
            }
            if ((user.getGameScore() > 0) || (user.getExpeScore() > 0)) {
               /* int gameType = UserParticipateRecord.checkUserId_3(user.getId());
                if (gameType != -3) {
                    result.put("isLogin", Boolean.FALSE);
                    result.put("messageStatus", 0);
                    //this.userServiceDao.updateStatus(user.getId(), 3);
                    GameService.gameKick(gameType, user.getId());
                    quitToLogin(user.getId(), 2);
                    //DealCheatThread.f(user.getId());
                    //再次调用主动退出，防止子游戏断线，通知不到服务器导致账号一直重复登录
                    gameService.logout(user.getId(), gameType, null);
                    return result;
                }*/
                clearingUserScore(user.getId());
                user = (User) this.userServiceDao.getById(user.getId());
            }
            GameParameterAssist.aR.remove(user.getId());

            session.setAttribute("username", user.getUsername());
            session.setAttribute("id", user.getId());
            GameParameterAssist.ba.put(user.getId(), session);
            GameParameterAssist.aF.add(user.getId());
        }
        if ((user.getPromoterId() == 0) && (user.getType() == 0)) {
            GameParameterAssist.aR.put(user.getId(), session);
        }
        session.setAttribute("trueClient", "true");
        result.put("isLogin", Boolean.TRUE);
        result.put("isShutup", config.getChat() == 0);
        Map<String, Object> gameRunStatus = new HashMap<>();
        gameRunStatus.put("joyGame", config.getOpenJoyGame());
        gameRunStatus.put("cardGame", config.getOpenCardGame());
        gameRunStatus.put("fishGame", config.getOpenFishGame());
        gameRunStatus.put("luckGame", config.getOpenLuckGame());
        gameRunStatus.put("WaterGame", config.getOpenWaterGame());
        gameRunStatus.put("bulletGame", config.getOpenBulletGame());
        gameRunStatus.put("mermaidGame", config.getOpenMermaidGame());
        gameRunStatus.put("ThousandGame", config.getOpenThousandFishGame());
        gameRunStatus.put("lackGame", config.getOpenLackGame());
        gameRunStatus.put("toadGame", config.getOpenToadGame());
        gameRunStatus.put("liKuiGame", config.getOpenLiKuiGame());
        gameRunStatus.put("benzBmwGame", config.getOpenBcbmGame());
        gameRunStatus.put("dragonTigerGame", config.getOpenDragonTigerGame());
        gameRunStatus.put("sharkGame", config.getOpenSharkGame());
        gameRunStatus.put("shareAddress", config.getShareAddress());
        gameRunStatus.put("TenThousandgame", 0);
        gameRunStatus.put("DiamondGame", 0);
        gameRunStatus.put("FishKingGame", 0);
        gameRunStatus.put("heavenGame", config.getOpenDntgGame());
        try {
            JSONObject liveGame = JSONObject.fromObject(config.getLiveGameJson());
            for (Object key : liveGame.keySet()) {
                gameRunStatus.put(key.toString(), liveGame.get(key));
            }
        } catch (Exception e) {
            logger.info("liveGame no config");
        }
        result.put("gameRunStatus", gameRunStatus);
        session.setAttribute("loginkey",  UUID.randomUUID());
        result.put("user", user);
        result.put("special", GameParameterAssist.special);
        Map<String, Object> functionOpen = new HashMap<>();
        functionOpen.put("notice", "0");//公告
        functionOpen.put("activity", "0");//活动
        functionOpen.put("exchange", config.getExpiry() > 0 ? "0" : "1");//兑换
        functionOpen.put("mail", "0");//邮件
        functionOpen.put("rank", "0");//排行榜
        functionOpen.put("topUp", config.getExpiry() > 0 ? "0" : "1");//充值
        functionOpen.put("setUp", "0");//设置
        result.put("functionOpen", functionOpen);
        this.userServiceDao.updateLoginDateById(user.getId(), MyUtil.c(), language);
        MessageSend.sendData(new StorageMethodEntity(session, "userLogin", new Object[]{result}));
        //Notice notice = this.noticeServiceDao.getNoticeByType();
        //MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "noticeList", new Object[]{notice}));
      //  com.miracle9.game.thread.UserRunnable.RunnableAfterLogin(session);
        UserParticipateRecord.removeUserIdMapCS(user.getId());
        LoginRecord loginRecord = new LoginRecord();
        loginRecord.setLoginDate(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
        loginRecord.setUserId(user.getId());
        loginRecord.setLoginIp((String) session.getAttribute("ip"));
        loginRecord.setUserType(2);
        this.loginRecordDao.addLoginRecord(loginRecord);
        return null;
    }

    public Map<String, Object> userLogin(String username, String password, int language, String versionCode, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        SystemConfig config = this.systemConfigServiceDao.q_CreateSqlFilter("from SystemConfig", new Object[0]);
        User user = this.userServiceDao.q_CreateSqlFilter("from User where username=?", new Object[]{username});
        if (config == null || user == null) {
            result.put("isLogin", Boolean.FALSE);
            result.put("messageStatus", 0);
            return result;
        }
        result.put("payMode", 0);
        result.put("accountProtectionState", 1);
        if (config.getRobotPromoter() != null && config.getRobotPromoter().equals(user.getPromoterName())) {
            result.put("updateAddress", config.getRobotUpdateAddress());
        } else {
            result.put("updateAddress", config.getUpdateAddress());
        }
        result.put("isLogin", Boolean.FALSE);
        result.put("messageStatus", -1);
        result.put("isShutup", Boolean.FALSE);
        result.put("user", null);
        if (!user.getPassword().equals(DigestUtils.md5Hex(password))) {
            result.put("isLogin", Boolean.FALSE);
            result.put("messageStatus", 0);
            return result;
        }
        if (user.getStatus() != 0) {
            result.put("isLogin", Boolean.FALSE);
            result.put("messageStatus", 1);
            return result;
        }
        if (config.getGameStatus() == 1 && user.getType() != 2) {
            result.put("isLogin", Boolean.FALSE);
            result.put("messageStatus", 2);
            return result;
        }
        if (!GameParameterAssist.ba.containsKey(user.getId())) {
            if (UserParticipateRecord.checkUserId_1(user.getId()) == 100) {
                result.put("isLogin", Boolean.FALSE);
                result.put("messageStatus", 15);
                synchronized (this) {
                    int nGameType = UserParticipateRecord.checkUserId_1(user.getId());
                    if (nGameType == 100) {
                        UserParticipateRecord.updateStatus(user.getId(), -1);
                    }
                }
                return result;
            }
        } else {
            logger.info("userId:[{}] 已经登录大厅了, 登录状态:[{}] !", user.getId(), UserParticipateRecord.checkUserId_1(user.getId()));
        }
        UserParticipateRecord.updateStatus(user.getId(), -1);
        synchronized (this) {
            if (isGameLogin(user.getId())) {
                quitToLogin(user.getId(), 4);
            } else {
                if (GameParameterAssist.ba.containsKey(user.getId())) {
                    IoSession lastClient = GameParameterAssist.ba.remove(user.getId());
                    Map<String, Object> ret = new HashMap<>();
                    ret.put("type", 4);
                    MessageSend.q.notifyAllOperating(new StorageMethodEntity(lastClient, "quitToLogin", new Object[]{ret}));
                    lastClient.removeAttribute("username");
                    lastClient.removeAttribute("id");
                    lastClient.setAttribute("needRemove", "true");
                }
                if ((user.getGameScore() > 0) || (user.getExpeScore() > 0)) {
                    int gameType = UserParticipateRecord.checkUserId_3(user.getId());
                    if (gameType != -3) {
                        result.put("isLogin", Boolean.FALSE);
                        result.put("messageStatus", 0);
                        //this.userServiceDao.updateStatus(user.getId(), 3);
                        GameService.gameKick(gameType, user.getId());
                        quitToLogin(user.getId(), 2);
                        //DealCheatThread.f(user.getId());
                        //再次调用主动退出，防止子游戏断线，通知不到服务器导致账号一直重复登录
                        gameService.logout(user.getId(), gameType, null);
                        return result;
                    }
                    clearingUserScore(user.getId());
                    user = (User) this.userServiceDao.getById(user.getId());
                }
                GameParameterAssist.aR.remove(user.getId());
            }
            session.setAttribute("username", user.getUsername());
            session.setAttribute("id", user.getId());
            GameParameterAssist.ba.put(user.getId(), session);
            GameParameterAssist.aF.add(user.getId());
        }
        if ((user.getPromoterId() == 0) && (user.getType() == 0)) {
            GameParameterAssist.aR.put(user.getId(), session);
        }
        session.setAttribute("trueClient", "true");
        result.put("isLogin", Boolean.TRUE);
        result.put("isShutup", config.getChat() == 0);
        Map<String, Object> gameRunStatus = new HashMap<>();
        gameRunStatus.put("joyGame", config.getOpenJoyGame());
        gameRunStatus.put("cardGame", config.getOpenCardGame());
        gameRunStatus.put("fishGame", config.getOpenFishGame());
        gameRunStatus.put("luckGame", config.getOpenLuckGame());
        gameRunStatus.put("WaterGame", config.getOpenWaterGame());
        gameRunStatus.put("bulletGame", config.getOpenBulletGame());
        gameRunStatus.put("mermaidGame", config.getOpenMermaidGame());
        gameRunStatus.put("ThousandGame", config.getOpenThousandFishGame());
        gameRunStatus.put("lackGame", config.getOpenLackGame());
        gameRunStatus.put("toadGame", config.getOpenToadGame());
        gameRunStatus.put("liKuiGame", config.getOpenLiKuiGame());
        gameRunStatus.put("benzBmwGame", config.getOpenBcbmGame());
        gameRunStatus.put("dragonTigerGame", config.getOpenDragonTigerGame());
        gameRunStatus.put("sharkGame", config.getOpenSharkGame());
        gameRunStatus.put("shareAddress", config.getShareAddress());
        gameRunStatus.put("TenThousandgame", 0);
        gameRunStatus.put("DiamondGame", 0);
        gameRunStatus.put("FishKingGame", 0);
        gameRunStatus.put("heavenGame", config.getOpenDntgGame());
        try {
            JSONObject liveGame = JSONObject.fromObject(config.getLiveGameJson());
            for (Object key : liveGame.keySet()) {
                gameRunStatus.put(key.toString(), liveGame.get(key));
            }
        } catch (Exception e) {
            logger.info("liveGame no config");
        }
        result.put("gameRunStatus", gameRunStatus);
        result.put("user", user);
        result.put("special", GameParameterAssist.special);
        Map<String, Object> functionOpen = new HashMap<>();
        functionOpen.put("notice", "0");//公告
        functionOpen.put("activity", "0");//活动
        functionOpen.put("exchange", config.getExpiry() > 0 ? "0" : "1");//兑换
        functionOpen.put("mail", "0");//邮件
        functionOpen.put("rank", "0");//排行榜
        functionOpen.put("topUp", config.getExpiry() > 0 ? "0" : "1");//充值
        functionOpen.put("setUp", "0");//设置
        result.put("functionOpen", functionOpen);
        this.userServiceDao.updateLoginDateById(user.getId(), MyUtil.c(), language);
        MessageSend.sendData(new StorageMethodEntity(session, "userLogin", new Object[]{result}));
        //Notice notice = this.noticeServiceDao.getNoticeByType();
        //MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "noticeList", new Object[]{notice}));
        com.miracle9.game.thread.UserRunnable.RunnableAfterLogin(session);
        UserParticipateRecord.removeUserIdMapCS(user.getId());
        LoginRecord loginRecord = new LoginRecord();
        loginRecord.setLoginDate(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
        loginRecord.setUserId(user.getId());
        loginRecord.setLoginIp((String) session.getAttribute("ip"));
        loginRecord.setUserType(2);
        this.loginRecordDao.addLoginRecord(loginRecord);
        return null;
    }



    public void getGameGold(int userId, IoSession session) {
        User user = (User) userServiceDao.getById(userId);
        Map<String, Object> result = new HashMap<>();
        result.put("gameGold", user.getGameGold());
        MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "newGameGold", new Object[]{result}));
    }

    public void afterLogin(IoSession session) {
        int userId = ((Integer) session.getAttribute("id"));
        User user = (User) this.userServiceDao.getById(userId);
        SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
        int unreadMail = this.userMailServiceDao.q_CreateSqlInt("select count(*) from UserMail where userId=? and status = 0", new Object[]{userId});
        List<UserAward> awards = this.userAwardServiceDao.q_CreateSqlList("from UserAward where userId=? and status=0 order by id", new Object[]{userId});
        if (!awards.isEmpty()) {
            this.userAwardServiceDao.q_CreateSql("update UserAward set status = 1 where userId=? and status=0", new Object[]{userId}).executeUpdate();
        }
        if (unreadMail > 0) {
            MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "newUserMail", new Object[0]));
        }
        for (UserAward ua : awards) {
            MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "userAward", new Object[]{ua.getGold()}));
        }
        Map<String, Object> chargeMap = new HashMap<>();
        chargeMap.put("status", config.getExpiry() == -1 ? 1 : 0);
        chargeMap.put("poportion", config.getPayScale());
        MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "chargeOpen", new Object[]{chargeMap}));
        List<PayApply> payApplys = this.payApplyServiceDao.q_CreateSqlList("from PayApply where notice=0 and userType=0 and state!=0 and userId=?", new Object[]{userId});
       /* for (PayApply p : (List)payApplys)
        {
          if (p.getState() == PayApply.PayApplyState.HANDLED) {
            chargeNotice(session, p);
          } else if (p.getType() == 0) {
            recharge(session);
          } else {
            excharge(session);
          }
          this.payApplyServiceDao.updateNotice(p.getId(), true);
        }*/
        for (PayApply payApply : payApplys) {
            if (payApply.getState() == PayApply.PayApplyState.HANDLED) {
                chargeNotice(session, payApply);
            } else if (payApply.getType() == 0) {
                recharge(session);
            } else {
                excharge(session);
            }
            this.payApplyServiceDao.updateNotice(payApply.getId(), true);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("newExpeGold", user.getExpeGold());
        MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "newExpeGold", new Object[]{result}));
        pubGoldNotice(user);
        ActivityInfo activityInfo = this.activityInfoServiceDao.getActivityInfo();
        if ((activityInfo != null) && (user.getPromoterId() == 0) && (user.getType() == 0)) {
            this.activityService.checkPayUserActivity(user.getId(), 0, 2);
            this.activityService.checkPlayUserActivity(userId);
            this.activityService.checkLevelUserActivity(user);
            int nNewFinishActivity = this.userActivityServiceDao.q_CreateSqlInt("select count(*) from UserActivity where userId=? and status = 1", new Object[]{Integer.valueOf(userId)});
            if (nNewFinishActivity > 0) {
                MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "newFinishActivity", new Object[]{Boolean.TRUE}));
            } else if (nNewFinishActivity == 0) {
                MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "newFinishActivity", new Object[]{Boolean.FALSE}));
            }
            Calendar calendar = Calendar.getInstance();
            int minute = calendar.get(12);
            int second = calendar.get(13);
            int hour = calendar.get(11);
            UserActivity newUserActivity = this.userActivityServiceDao.getByUserIdAndTypeAndNCondition1(userId, 6, hour);
            if ((newUserActivity != null) && (GameParameterAssist.aG.size() != 0)) {
                for (Integer bonusTime : GameParameterAssist.aH.values()) {
                    if (bonusTime != null) {
                        if (newUserActivity.getBonusCount() != 3) {
                            int lastBonusTime = (bonusTime - minute + 4) * 60 + (60 - second);
                            if ((lastBonusTime > 0) && (GameParameterAssist.aG.size() == 0)) {
                                MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "startBonusRain", new Object[]{-1}));
                            } else if (lastBonusTime > 0) {
                                MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "startBonusRain", new Object[]{lastBonusTime}));
                            }
                        }
                    }
                }
            }
        }
    }

    public boolean checkUsername(String username, IoSession session) {
        int count = this.userServiceDao.q_CreateSqlInt("select count(*) from User where username=?", new Object[]{username});
        return count > 0;
    }

    public void ignoreCheckInformation(int status, IoSession session) {
        int userId = ((Integer) session.getAttribute("id"));
        User user = (User) this.userServiceDao.getById(userId);
        if (status == 0) {
            user.setCard("-2");
            this.userServiceDao.update(user);
        } else if (status == 1) {
            user.setCard("-1");
            this.userServiceDao.update(user);
        }
    }

    public Map<String, Object> addInformation(String card, String phone, String question, String answer, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        int userId = ((Integer) session.getAttribute("id"));
        User user = (User) this.userServiceDao.getById(userId);
        user.setCard(card);
        user.setQuestion(question);
        user.setAnswer(answer);
        try {
            this.userServiceDao.update(user);
            result.put("success", Boolean.TRUE);
            return result;
        } catch (Exception e) {
            result.put("success", Boolean.FALSE);
        }
        return result;
    }

    public Map<String, Object> checkInformation(IoSession session) {
        Map<String, Object> result = new HashMap<>();
        int userId = ((Integer) session.getAttribute("id"));
        User user = (User) this.userServiceDao.getById(userId);
        if (user.getCard().endsWith("-1")) {
            result.put("status", 1);
        } else if (user.getCard().endsWith("-2")) {
            result.put("status", 2);
        } else {
            result.put("status", 0);
        }
        return result;
    }

    public Map<String, Object> isRegistOK(String username, IoSession session) {
        logger.info("is RegistOK username:" + username);
        int applyStatus = this.userRegistLogServiceDao.getApplyStatusByUsername(username);
        Map<String, Object> result = new HashMap<>();
        result.put("success", Boolean.TRUE);
        result.put("messageStatus", Integer.valueOf(applyStatus));
        return result;
    }

    public Map<String, Object> updateUserInfo(String paramString1, String paramString2, int paramInt, IoSession paramIoSession) {
        return updateNickname(paramString1, paramString2.charAt(0), paramInt, paramIoSession);
    }

    public Map<String, Object> register(Map<String, Object> paramMap, IoSession paramIoSession) {
        Map<String, Object> result = new HashMap<>();

        try {
            String str1 = JSONObject.fromObject(paramMap).toString().replaceAll("null", "\"\"").replaceAll("promoterUsername", "promoterName");
            logger.info("register =" + str1);
            User localUser = (User) JSONObject.toBean(JSONObject.fromObject(str1), User.class);
            SystemConfig localSystemConfig = this.systemConfigServiceDao.getSystemConfig();
            int i = this.userServiceDao.q_CreateSqlInt("select count(*) from User where username=?", new Object[]{localUser.getUsername()});
            if (i > 0) {
                result.put("isRegister", Boolean.FALSE);
                result.put("msgCode", 4);
                result.put("msg", "用户名重复");
                return result;
            }
            //如果是机器人代理则临时改为独家代理
            if(localSystemConfig.getRobotPromoter().equals(localUser.getPromoterName())){
                localSystemConfig.setProxyMode(0);
            }
            //独家代理
            if (localSystemConfig.getProxyMode() == 0) {
                if ((StringUtils.isBlank(localUser.getPromoterName())) || (localUser.getPromoterName().equals("admin"))) {
                    localUser.setPromoterId(0);
                    localUser.setPromoterName("admin");
                } else {
                    Promoter localPromoter = this.promoterServiceDao1.q_CreateSqlFilter("from Promoter where username=?", new Object[]{localUser.getPromoterName()});
                    if (localPromoter == null) {
                        result.put("isRegister", Boolean.FALSE);
                        result.put("msgCode", 5);
                        result.put("msg", "推广员不存在");
                        return result;
                    }
                    localUser.setPromoterId(localPromoter.getId());
                    localUser.setPromoterName(localPromoter.getUsername());
                }
            }
            User promoterUser = null;
            //全民代理
            if (localSystemConfig.getProxyMode() == 1) {
                promoterUser = this.userServiceDao.q_CreateSqlFilter("from User where id=?", new Object[]{Integer.valueOf(localUser.getPromoterName())});
                if (promoterUser == null) {
                    result.put("isRegister", Boolean.FALSE);
                    result.put("msgCode", 5);
                    result.put("msg", "邀请码不存在");
                    return result;
                }
                localUser.setParentId(promoterUser.getId());
            }
            localUser.setPassword(DigestUtils.md5Hex(localUser.getPassword()));
            if (localSystemConfig.getRegistVerify() == 1) {
                int j = this.userRegistLogServiceDao.getQuantityByUsername(localUser.getUsername());
                logger.info("applyReigstCount:" + j);
                if (j > 0) {
                    result.put("isRegister", Boolean.FALSE);
                    result.put("msgCode", -4);
                    result.put("msg", "等待后台验证");
                    return result;
                }
                String str2 = ((InetSocketAddress) paramIoSession.getRemoteAddress()).getAddress().getHostAddress();
                UserRegistLog localUserRegistLog = null;
                //独家代理
                if (localSystemConfig.getProxyMode() == 0) {
                    localUserRegistLog = UserRegistLog.create(localUser.getUsername(), localUser.getUsername(), localUser.getPromoterName(), localUser.getPromoterId(), localUser.getPhone(), str2, localUser.getPassword());
                }
                //全民代理
                if (localSystemConfig.getProxyMode() == 1) {
                    localUserRegistLog = UserRegistLog.create(localUser.getUsername(), localUser.getNickname(), promoterUser.getUsername(), promoterUser.getId(), localUser.getPhone(), str2, localUser.getPassword());
                }
                boolean bool = this.userRegistLogService.addRegistApply(localUserRegistLog);
                if (bool) {
                    result.put("isRegister", Boolean.FALSE);
                    result.put("success", Boolean.TRUE);
                    result.put("msgCode", -4);
                    return result;
                }
                result.put("isRegister", Boolean.FALSE);
                result.put("msgCode", 6);
                result.put("msg", "注册失败");
                return result;
            }
            localUser.setId(0);
            regist(localUser, localSystemConfig);
        } catch (Exception localException) {
            logger.error("", localException);
            result.put("isRegister", Boolean.FALSE);
            result.put("msgCode", 6);
            result.put("msg", "注册失败");
            MessageSend.q.notifyAllOperating(new StorageMethodEntity(paramIoSession, "register", new Object[]{result}));
            throw new RuntimeException();
        }
        result.put("isRegister", Boolean.TRUE);
        result.put("messageStatus", -1);
        return result;
    }

    /*public Map<String, Object> regist(User user, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
        if ((user.getType() == 1) && (config.getRegistVerify() == 1)) {
            logger.info("游客登录，注册验证开启");
            result.put("success", Boolean.TRUE);
            result.put("messageStatus", -2);
            return result;
        }
        try {
            int count = this.userServiceDao.q_CreateSqlInt("select count(*) from User where username=?", new Object[]{user.getUsername()});
            if (count > 0) {
                result.put("success", Boolean.FALSE);
                result.put("messageStatus", 1);
                return result;
            }
            if ((StringUtils.isBlank(user.getPromoterName())) || (user.getPromoterName().equals("admin"))) {
                user.setPromoterId(0);
                user.setPromoterName("admin");
            } else {
                Promoter promoter = (Promoter) this.promoterServiceDao1.q_CreateSqlFilter("from Promoter where username=?", new Object[]{user.getPromoterName()});
                if (promoter == null) {
                    result.put("success", Boolean.FALSE);
                    result.put("messageStatus", 2);
                    return result;
                }
                user.setPromoterId(promoter.getId());
            }
            user.setPassword(DigestUtils.md5Hex(user.getPassword()));
            if (config.getRegistVerify() == 1) {
                logger.info("注册，注册验证开启");
                int applyReigstCount = this.userRegistLogServiceDao.getQuantityByUsername(user.getUsername());
                logger.info("applyReigstCount:" + applyReigstCount);
                if (applyReigstCount > 0) {
                    result.put("success", Boolean.FALSE);
                    result.put("messageStatus", 1);
                    return result;
                }
                String ip = ((InetSocketAddress) session.getRemoteAddress()).getAddress().getHostAddress();
                UserRegistLog userRegistLog = UserRegistLog.create(user.getUsername(), user.getNickname(), user.getPromoterName(), user.getPromoterId(), user.getPhone(), ip, user.getPassword());
                boolean success = this.userRegistLogService.addRegistApply(userRegistLog);
                if (success) {
                    result.put("success", Boolean.TRUE);
                    result.put("messageStatus", -2);
                } else {
                    result.put("success", Boolean.FALSE);
                    result.put("messageStatus", -3);
                }
                return result;
            }
            regist(user);
        } catch (Exception e) {
            logger.error("", e);
            result.put("success", Boolean.FALSE);
            result.put("messageStatus", -1);
            MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "regist", new Object[]{result}));
        }
        result.put("success", Boolean.TRUE);
        result.put("messageStatus", -1);
        return result;
    }*/

    public String getRandomNumber() {
        String SYMBOLS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random RANDOM = new SecureRandom();
        char[] nonceChars = new char[6];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    /**
     * 添加用户
     *
     * @param user
     */
    public void regist(User user, SystemConfig systemConfig) {
        Random random = new Random();
        user.setPassword(user.getPassword());
        user.setRegistDate(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
        user.setLoginDate("");
        user.setStatus(0);
        user.setGameGold(0);
        user.setExpeGold(0);
        user.setOverflow(0);
        user.setLevel(1);
        user.setLevelScore(0.0D);
        user.setShutupStatus(0);
        user.setLastDeskId(-1);
        user.setSex(random.nextInt(2) == 0 ? '男' : '女');
        user.setBoxGameGold(0);
        user.setBoxLottery(0);
        user.setSecurity(123456);
        user.setPhone("-");
        user.setCard("-1");
        user.setQuestion("-1");
        user.setAnswer("-1");

        //独家代理
        if (systemConfig.getProxyMode() == 0) {
            this.promoterServiceDao1.q_Update("update Promoter set childrenUserNum = childrenUserNum+1 where id=?", new Object[]{user.getPromoterId()});
        }
        this.userServiceDao.save(user);
        //全民代理
        if (systemConfig.getProxyMode() == 1) {
            RechargeActivity rechargeActivity = new RechargeActivity();
            rechargeActivity.setAmount(new BigDecimal(192.56));
            rechargeActivity.setBalance(BigDecimal.ZERO);
            rechargeActivity.setUserId(user.getId());
            rechargeActivity.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
            this.rechargeActivityServiceDao.save(rechargeActivity);
            this.promoterServiceDao1.q_Update("update User set sonNUm = sonNUm+1 where id=?", new Object[]{user.getParentId()});
        }
        String hql = "update User set nickname=? where id=?";
        Query query = userServiceDao.q_CreateSql(hql, new Object[]{"VIP" + user.getId(), user.getId()});
        query.executeUpdate();
        UserWarning userWarning = new UserWarning();
        userWarning.setUserId(user.getId());
        userWarning.setGameGold(user.getGameGold());
        addUserWarning(userWarning);
        UserWarningBak userWarningBak = new UserWarningBak();
        userWarningBak.setUserId(user.getId());
        userWarningBak.setGameGold(user.getGameGold());
        userWarningBak.setDate(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
        addUserWarningBak(userWarningBak);
        List<Activity> activities = this.activityServiceDao.getActivityList();
        if ((user.getPromoterId() == 0) && (user.getType() == 0)) {
            for (Activity activity : activities) {
                if (activity.getType() == 3) {
                    activity.setCondition2(user.getLevel());
                }
                UserActivity userActivity = new UserActivity(user.getId(), activity.getId(), activity.getContent(), activity.getContentEn(), activity.getAwardGold(), 0, activity.getType(), 0, 0, 0, 0, activity.getCondition1(), activity.getCondition2(), activity.getCondition3());
                this.userActivityServiceDao.saveReturnInteger(userActivity);
                IoSession s = GameParameterAssist.ba.get(user.getId());
                if (s != null) {
                    MessageSend.q.notifyAllOperating(new StorageMethodEntity(s, "newUserActivity", new Object[]{activity.getType()}));
                }
            }
        }
        //机器人代理，注册成功充值游戏币
        if (user.getPromoterName() != null && user.getPromoterName().equals(systemConfig.getRobotPromoter()) && systemConfig.getRobotGold() > 0) {
            pay(user.getId(), systemConfig.getRobotGold(), 0, null);
        }
    }

    public Map<String, Object> updateNickname(String nickname, Character sex, int photoId, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = Integer.parseInt(session.getAttribute("id").toString());
            this.userServiceDao.updateById(userId, nickname, sex, photoId);
            result.put("success", Boolean.TRUE);
            result.put("message", "修改成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", Boolean.FALSE);
            result.put("message", "系统异常！");
        }
        return result;
    }

    public Map<String, Object> updatePassword(String oldPassword, String newPassword, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = Integer.parseInt(session.getAttribute("id").toString());
            User user = (User) this.userServiceDao.getById(userId);
            if (user.getPassword().equals(DigestUtils.md5Hex(oldPassword))) {
                this.userServiceDao.updatePasswordById(userId, DigestUtils.md5Hex(newPassword));
                result.put("success", Boolean.TRUE);
                result.put("message", "修改成功！");
            } else {
                result.put("success", Boolean.FALSE);
                result.put("message", "原密码错误！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", Boolean.FALSE);
            result.put("message", "系统异常！");
        }
        return result;
    }

    public Map<String, Object> addExpeGold(IoSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = Integer.parseInt(session.getAttribute("id").toString());
            User user = (User) this.userServiceDao.getById(userId);
            if (user.getExpeGold() >= 10000) {
                result.put("success", Boolean.FALSE);
                result.put("message", "体验币小于10000时才能领取！");
                result.put("msgCode", 15);
            } else {
                this.userServiceDao.updateExpeGoldById(userId, 10000);
                result.put("success", Boolean.TRUE);
                result.put("message", "领取成功！");
                result.put("expeGold", 10000);
                MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "newExpeGold", new Object[]{10000}));
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", Boolean.FALSE);
            result.put("message", "系统异常！");
        }
        return result;
    }

    public void exitGame(IoSession session) {
        try {
            Integer userId = Integer.parseInt(session.getAttribute("id").toString());
            session.removeAttribute("username");
            session.removeAttribute("id");
            GameParameterAssist.ba.remove(userId);
            GameParameterAssist.aR.remove(userId);
        } catch (Exception e) {
            logger.error("exitGame," + e);
        }
    }

    public void clearingUserScore(int userId) {
        try {
            User user = (User) this.userServiceDao.getById(userId);
            logger.info(String.valueOf(user.getUsername()) + "，" + user.getGameGold() + "，" + user.getGameScore());
            int exchange = getDeskExchange(user);
            if (user.getGameScore() > 0) {
                int addGold = user.getGameScore() / exchange;
                if (user.getGameScore() % exchange != 0) {
                    int odd = user.getGameScore() % exchange;
                    int per = odd / exchange;
                    int range = per * 100;
                    Random random = new Random();
                    if (random.nextInt(100) < range) {
                        addGold++;
                    }
                }
                this.userServiceDao.updateGameById(userId, addGold, -user.getGameScore());
                logger.info("结算用户游戏分值");
            } else if (user.getGameScore() < 0) {
                this.userServiceDao.updateGameById(userId, 0, -user.getGameScore());
            }
            if (user.getExpeScore() > 0) {
                int addGold = user.getExpeScore() / exchange;
                if (user.getExpeScore() % exchange != 0) {
                    int odd = user.getExpeScore() % exchange;
                    int per = odd / exchange;
                    int range = per * 100;
                    Random random = new Random();
                    if (random.nextInt(100) < range) {
                        addGold++;
                    }
                }
                this.userServiceDao.updateExpeByIdAndIf(userId, addGold, -user.getExpeScore());
                logger.info("结算用户体验分值");
            } else if (user.getExpeScore() < 0) {
                this.userServiceDao.updateExpeByIdAndIf(userId, 0, -user.getExpeScore());
            }
        } catch (Exception e) {
            logger.error("结算出错" + userId, e);
        }
    }

    public Map<String, Object> pay(int userId, int money, int type, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        result.put("type", type);
        if (money <= 0) {
            return null;
        }
        String datetime = MyUtil.dateFormatYMD_HMS_Sting(new Date());
        SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
        User user = (User) this.userServiceDao.getById(userId);
        if (user.getOverflow() == 1) {
            result.put("success", Boolean.FALSE);
            result.put("message", MyUtil.getProperties(resultInt(session), "userMoneyOverrun"));
            result.put("plusGold", 0);
            return result;
        }
        Integer adminId = session == null ? 1 : Integer.parseInt(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        int payCount = this.payLogServiceDao.q_CreateSqlInt("select count(*) from PayLog where type = 0 and admin = ? and datetime = ?", new Object[]{admin.getUsername(), datetime});
        if (payCount > 0) {
            return null;
        }
        int gold = MyUtil.moneyExchange(money, config.getPayScale());
        PayApply payApply = null;
        PayLog payLog = new PayLog();
        synchronized (PayApplyService.expiryLock) {
            if (type == 1) {
                payApply = this.payApplyServiceDao.getByuserIdAndUserType_0(userId, 0);
                if (payApply == null) {
                    result.put("success", Boolean.FALSE);
                    result.put("message", MyUtil.getProperties(resultInt(session), "payTimeout"));
                    return result;
                }
            }
            Busine busine = this.busineServiceDao.getAndSave();
            int waiter = admin.getType() == 3 ? 1 : 0;
            if (config.getSwitchType() != -1) {
                if ((busine.getStatus() != 0) && (admin.getType() == 3)) {
                    result.put("success", Boolean.FALSE);
                    result.put("message", MyUtil.getProperties(resultInt(session), "pauseBusine"));
                    result.put("plusGold", 0);
                    return result;
                }
                if (busine.getStatus() == 2) {
                    this.busineInfoTempServiceDao.save(new BusineInfoTemp(admin.getUsername(), MyUtil.dateFormatYMD_HMS_Sting(new Date()), money, 0.0D, 0, 0));
                } else {
                    BusineInfo info = this.busineInfoServiceDao.getBusineInfo(admin.getUsername(), busine.getId(), busine.getCurrentShiftType());
                    if (info == null) {
                        info = new BusineInfo();
                        info.setBusineId(busine.getId());
                        info.setStartTime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
                        info.setCurrentShiftType(busine.getCurrentShiftType());
                        info.setPayCount(money);
                        info.setAdmin(admin.getUsername());
                        info.setWaiter(waiter);
                        this.busineInfoServiceDao.save(info);
                    } else {
                        if (info.getShiftWorkStatus() == 1) {
                            result.put("success", Boolean.FALSE);
                            result.put("message", MyUtil.getProperties(resultInt(session), "jiaobanOperationError"));
                            result.put("plusGold", 0);
                            return result;
                        }
                        info.setPayCount(info.getPayCount() + money);
                        this.busineInfoServiceDao.update(info);
                    }
                }
                this.busineLogServiceDao.save(new BusineLog(user.getUsername(), MyUtil.dateFormatYMD_HMS_Sting(new Date()), money, gold, admin.getUsername(), BusineLog.BusineType.PAY));
            }
            if (type == 1) {
                payLog.setRemark(payApply.getRemark());
                List<PayApply> logs = this.payApplyServiceDao.getAllPayApply();
                for (PayApply ul : logs) {
                    if (ul.getId() == payApply.getId()) {
                        logs.remove(ul);
                        break;
                    }
                }
                payApply.setState(PayApply.PayApplyState.HANDLED);
                payApply.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
                payApply.setAmmount(gold);
                this.userServiceDao.updatePayMoney(userId, 0);
                IoSession hallSession = GameParameterAssist.ba.get(userId);
                if (hallSession != null) {
                    payApply.setNotice(true);
                    chargeNotice(hallSession, payApply);
                }
                this.payApplyServiceDao.update(payApply);
                Object countMap = getUserPayCount();
                for (IoSession as : GameParameterAssist.be.values()) {
                    AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(as, "userPayCount", new Object[]{countMap}));
                }
            } else if (type == 0) {
                payApply = new PayApply(MyUtil.dateFormatYMD_HMS_Sting(new Date()), gold, userId, "", null, System.currentTimeMillis() + config.getExpiry() * 6000000L, 0, 0, false);
                this.payApplyServiceDao.save(payApply);
                this.payApplyServiceDao.getAllPayApply().add(payApply);
                List<PayApply> logs2 = this.payApplyServiceDao.getAllPayApply();
                for (PayApply ul : logs2) {
                    if (ul.getId() == payApply.getId()) {
                        logs2.remove(ul);
                        break;
                    }
                }
                payApply.setState(PayApply.PayApplyState.HANDLED);
                payApply.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
                payApply.setAmmount(gold);
                IoSession hallSession = GameParameterAssist.ba.get(userId);
                if (hallSession != null) {
                    payApply.setNotice(true);
                    chargeNotice(hallSession, payApply);
                }
                this.payApplyServiceDao.update(payApply);
            }
        }
        this.userWarningServiceDao.updatePayCountByUid(userId, gold);
        this.userServiceDao.updateGameById(user.getId(), gold, 0);
        user = (User) this.userServiceDao.getById(userId);
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        result.put("plusGold", gold);
        payLog.setExpiryType(type);
        payLog.setUserId(user.getId());
        payLog.setUsername(user.getUsername());
        payLog.setAdmin(admin.getUsername());
        payLog.setType(0);
        payLog.setDatetime(datetime);
        payLog.setMoney(money);
        payLog.setGold(gold);
        payLog.setAuthority(admin.getType());
        User user2 = (User) this.userServiceDao.getById(userId);
        payLog.setGameGold(user2.getGameGold() + user2.getExpiryNum());
        this.payLogServiceDao.save(payLog);
        pubGoldNotice(user);
        if ((user.getPromoterId() == 0) && (user.getType() == 0)) {
            this.activityService.checkPayUserActivity(user.getId(), gold, 1);
        }
        double userMoney = MyUtil.goldExchange(user.getGameGold(), config.getPayScale());
        if ((config.getMoneyOverrun() != -1) && (userMoney >= config.getMoneyOverrun())) {
            this.userServiceDao.updateOverflow(userId, 1);
            pubOverflowNotice(userId);
        }
        String content = MyUtil.format("为直属会员{0}充值{1}元", user.getUsername(), money);
        String contentEn = MyUtil.format("Recharge {0} yuan for direct member which ID is {1}", money, user.getUsername());
        AdminLog adminLog = new AdminLog(admin.getUsername(), content, 2, admin.getType(), contentEn);
        this.adminLogServiceDao.addAdminLog(adminLog);
        return result;
    }

    public static void pubOverflowNotice(int userId) {
        if (GameParameterAssist.ba.containsKey(userId)) {
            MessageSend.q.notifyAllOperating(new StorageMethodEntity(GameParameterAssist.ba.get(userId), "overflow", new Object[0]));
        }
        for (GameTypeSession gameTypeSession : SessionUtils.getSessionByUserId(userId)) {
            for (IoSession session : gameTypeSession.getSessionSet()) {
                AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(session, "manageService/overflow", new Object[]{userId}));
            }
        }
    }

    public Map<String, Object> expiry(int userId, int gold, int type, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        result.put("type", type);
        if (gold <= 0) {
            return null;
        }
        User user = (User) this.userServiceDao.getById(userId);
        PayApply expiryLog = null;
        synchronized (PayApplyService.expiryLock) {
            if (type == 0) {
                if (gold > user.getGameGold()) {
                    result.put("success", Boolean.FALSE);
                    result.put("message", MyUtil.getProperties(resultInt(session), "notGold"));
                    return result;
                }
            } else {
                expiryLog = this.payApplyServiceDao.getByuserIdAndUserType_0(userId, PayApply.PayApplyType.EXPIRY.ordinal());
                if (expiryLog == null) {
                    result.put("success", Boolean.FALSE);
                    result.put("message", MyUtil.getProperties(resultInt(session), "expiryTimeout"));
                    return result;
                }
                gold = expiryLog.getAmmount();
            }
            Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
            Admin admin = (Admin) this.adminServiceDao.getById(adminId);
            SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
            double money = MyUtil.doubleDivideCalculation(gold * config.getPayScale(), 100.0D);
            Busine busine = this.busineServiceDao.getAndSave();
            BusineInfo info = null;
            int waiter = admin.getType() == 3 ? 1 : 0;
            if (config.getSwitchType() != -1) {
                if ((busine.getStatus() != 0) && (admin.getType() == 3)) {
                    result.put("success", Boolean.FALSE);
                    result.put("message", MyUtil.getProperties(resultInt(session), "pauseBusine"));
                    result.put("plusGold", 0);
                    return result;
                }
                if (busine.getStatus() == 2) {
                    this.busineInfoTempServiceDao.save(new BusineInfoTemp(admin.getUsername(), MyUtil.dateFormatYMD_HMS_Sting(new Date()), 0, money, 0, 0));
                } else {
                    info = this.busineInfoServiceDao.getBusineInfo(admin.getUsername(), busine.getId(), busine.getCurrentShiftType());
                    if (info == null) {
                        info = new BusineInfo();
                        info.setBusineId(busine.getId());
                        info.setStartTime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
                        info.setCurrentShiftType(busine.getCurrentShiftType());
                        info.setExchangeCount(0.0D);
                        info.setAdmin(admin.getUsername());
                        info.setWaiter(waiter);
                        this.busineInfoServiceDao.save(info);
                    } else if (info.getShiftWorkStatus() == 1) {
                        result.put("success", Boolean.FALSE);
                        result.put("message", MyUtil.getProperties(resultInt(session), "jiaobanOperationError"));
                        result.put("plusGold", 0);
                        return result;
                    }
                }
                this.busineLogServiceDao.save(new BusineLog(user.getUsername(), MyUtil.dateFormatYMD_HMS_Sting(new Date()), money, gold, admin.getUsername(), BusineLog.BusineType.EXPIRY));
            }
            PayLog payLog = new PayLog();
            payLog.setUserId(user.getId());
            payLog.setUsername(user.getUsername());
            payLog.setAdmin(admin.getUsername());
            payLog.setType(1);
            payLog.setExpiryType(type);
            payLog.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
            payLog.setMoney(money);
            payLog.setGold(gold);
            payLog.setAuthority(admin.getType());
            User user2 = (User) this.userServiceDao.getById(userId);
            payLog.setGameGold(user2.getGameGold() + user2.getExpiryNum());
            List<PayApply> logs;
            double userMoney;
            if (type == 0) {
                int count = this.userServiceDao.updateGameById(userId, -gold, 0);
                if (count <= 0) {
                    result.put("success", Boolean.FALSE);
                    result.put("message", MyUtil.getProperties(resultInt(session), "notGold"));
                    return result;
                }
                user = (User) this.userServiceDao.getById(userId);
                IoSession s = GameParameterAssist.ba.get(user.getId());
                pubGoldNotice(user);
                expiryLog = new PayApply(MyUtil.dateFormatYMD_HMS_Sting(new Date()), gold, userId, "", null, System.currentTimeMillis() + config.getExpiry() * 6000000L, 0, 1, false);
                this.payApplyServiceDao.save(expiryLog);
                this.payApplyServiceDao.getAllPayApply().add(expiryLog);
                logs = this.payApplyServiceDao.getAllPayApply();
                for (PayApply ul : logs) {
                    if (ul.getId() == expiryLog.getId()) {
                        logs.remove(ul);
                        break;
                    }
                }
                expiryLog.setState(PayApply.PayApplyState.HANDLED);
                expiryLog.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
                expiryLog.setAmmount(gold);
                this.payApplyServiceDao.update(expiryLog);
                IoSession hallSession = GameParameterAssist.ba.get(userId);
                if (hallSession != null) {
                    expiryLog.setNotice(true);
                    chargeNotice(hallSession, expiryLog);
                }
                this.payApplyServiceDao.update(expiryLog);
                if (user.getOverflow() == 1) {
                    userMoney = MyUtil.goldExchange(user.getGameGold(), config.getPayScale());
                    if (userMoney < config.getMoneyOverrun()) {
                        this.userServiceDao.updateOverflow(userId, 0);
                        if (s != null) {
                            MessageSend.q.notifyAllOperating(new StorageMethodEntity(s, "unOverflow", new Object[0]));
                        }
                    }
                }
            } else {
                expiryLog.setState(PayApply.PayApplyState.HANDLED);
                expiryLog.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
                List<PayApply> logs2 = this.payApplyServiceDao.getAllPayApply();
                for (PayApply ul2 : logs2) {
                    if (ul2.getId() == expiryLog.getId()) {
                        logs2.remove(ul2);
                        break;
                    }
                }
                this.userServiceDao.updateExpiryNum(userId, 0);
                payLog.setRemark(expiryLog.getRemark());
                IoSession hallSession2 = GameParameterAssist.ba.get(userId);
                if (hallSession2 != null) {
                    expiryLog.setNotice(true);
                    chargeNotice(hallSession2, expiryLog);
                }
                this.payApplyServiceDao.update(expiryLog);
                Map<String, Object> countMap = getUserPayCount();
                for (IoSession as : GameParameterAssist.be.values()) {
                    AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(as, "userPayCount", new Object[]{countMap}));
                }
            }
            this.payLogServiceDao.save(payLog);
            if (busine.getStatus() != 2) {
                info.setExchangeCount(info.getExchangeCount() + money);
                this.busineInfoServiceDao.update(info);
            }
            result.put("success", Boolean.TRUE);
            result.put("message", "");
            result.put("plusGold", gold);
            int nFlag = this.userWarningServiceDao.updateExpiryCountByUid(userId, gold);
            if (nFlag == -1) {
                result.put("success", Boolean.FALSE);
                result.put("message", MyUtil.getProperties(resultInt(session), "systemError"));
                return result;
            }
            String content = MyUtil.format("为直属会员{0}兑换{1}元", user.getUsername(), money);
            String contentEn = MyUtil.format("Exchange {0} coins for direct member which ID is {1}", money, user.getUsername());
            AdminLog adminLog = new AdminLog(admin.getUsername(), content, 2, admin.getType(), contentEn);
            this.adminLogServiceDao.addAdminLog(adminLog);
            return result;
        }
    }

    public static void pubGoldNotice(User user) {
        if (GameParameterAssist.ba.containsKey(user.getId())) {
            Map<String, Object> result = new HashMap<>();
            result.put("gameGold", user.getGameGold());
            MessageSend.q.notifyAllOperating(new StorageMethodEntity(GameParameterAssist.ba.get(user.getId()), "newGameGold", new Object[]{result}));
        }
        for (GameTypeSession gameTypeSession : SessionUtils.getSessionByUserId(user.getId())) {
            for (IoSession session : gameTypeSession.getSessionSet()) {
                AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(session, "manageService/newGameGold", new Object[]{user.getId(), user.getGameGold()}));
            }
        }
    }

    public Map<String, Object> getUser(String username, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = this.userServiceDao.q_CreateSqlFilter("from User where username=?", new Object[]{username});
        if (user == null) {
            result.put("success", Boolean.FALSE);
            result.put("message", MyUtil.getProperties(resultInt(session), "usernameNotExist"));
            result.put("user", null);
            return result;
        }
        Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
        Busine busine = this.busineServiceDao.getAndSave();
        if ((admin.getType() == 3) && (config.getSwitchType() != -1) && (busine.getStatus() != 0)) {
            result.put("success", Boolean.FALSE);
            result.put("message", MyUtil.getProperties(resultInt(session), "pauseBusine"));
            result.put("user", null);
            return result;
        }
        if (admin.getType() == 3) {
            BusineInfo info = this.busineInfoServiceDao.getBusineInfo(admin.getUsername(), busine.getId(), busine.getCurrentShiftType());
            if ((info != null) && (info.getShiftWorkStatus() == 1)) {
                result.put("success", Boolean.FALSE);
                result.put("message", MyUtil.getProperties(resultInt(session), "jiaobanOperationError"));
                result.put("user", null);
                return result;
            }
        }
        int count = this.computerOrderServiceDao.q_CreateSqlInt("select count(*) from ComputerOrder where user.id=? and status=0", new Object[]{user.getId()});
        if (count > 0) {
            user.setBorrow(1);
        } else {
            user.setBorrow(0);
        }
        user.setDisplayStatus(0);
        if (user.getStatus() == 1) {
            user.setDisplayStatus(1);
        } else if (user.getOverflow() == 1) {
            user.setDisplayStatus(2);
        } else if (user.getShutupStatus() != 0) {
            user.setDisplayStatus(3);
        } else if (user.getStatus() == 2) {
            user.setDisplayStatus(4);
        } else if (user.getStatus() == 3) {
            user.setDisplayStatus(5);
        }
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        result.put("user", user);
        return result;
    }

    public void addUserScore(int id, int gameScore, int expeScore, double levelScore) {
        this.userServiceDao.addUserScore(id, gameScore, expeScore, levelScore);
    }

    public Map<String, Object> enterUserPwd(int userId, String pwd, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        int count = this.userServiceDao.q_CreateSqlInt("select count(*) from User where id=? and password=?", new Object[]{Integer.valueOf(userId), DigestUtils.md5Hex(pwd)});
        if (count <= 0) {
            result.put("success", Boolean.FALSE);
            result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "passwordError"));
            return result;
        }
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        return result;
    }

    public boolean enterSelfPwd(String password, IoSession session) {
        Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        return MyUtil.strPwdMd5Hex(password).equals(admin.getPassword());
    }

    public Map<String, Object> enterSuperPwd(String username, String password, int type, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        int count = this.adminServiceDao.q_CreateSqlInt("select count(*) from Admin where username=? and password = ? and (type=0 or type=1)", new Object[]{username, MyUtil.strPwdMd5Hex(password)});
        if (count > 0) {
            SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
            if (type == 0) {
                if (config.getTempSumPayMoney() > 0) {
                    config.setTempSumPayMoney(config.getTempSumPayMoney() + config.getSumPayMoney());
                } else {
                    config.setTempSumPayMoney(config.getSumPayMoney() * 2);
                }
            } else if (type == 1) {
                if (config.getTempSumExpiryMoney() > 0) {
                    config.setTempSumExpiryMoney(config.getTempSumExpiryMoney() + config.getSumExpiryMoney());
                } else {
                    config.setTempSumExpiryMoney(config.getSumExpiryMoney() * 2);
                }
            } else if (type == 2) {
                if (config.getTempUserSumMoney() > 0) {
                    config.setTempUserSumMoney(config.getTempUserSumMoney() + config.getUserSumMoney());
                } else {
                    config.setTempUserSumMoney(config.getUserSumMoney() * 2);
                }
            } else if (type == 3) {
                if (config.getTempPromoterSumMoney() > 0) {
                    config.setTempPromoterSumMoney(config.getTempPromoterSumMoney() + config.getPromoterSumMoney());
                } else {
                    config.setTempPromoterSumMoney(config.getPromoterSumMoney() * 2);
                }
            }
            this.systemConfigServiceDao.updateAlltemp(config);
            result.put("success", Boolean.TRUE);
            result.put("message", "");
            result.put("type", type);
        } else {
            result.put("success", Boolean.FALSE);
            result.put("message", MyUtil.getProperties(resultInt(session), "adminUsernameOrPwdError"));
            result.put("type", type);
        }
        return result;
    }

    public int checkSumPay(int money, IoSession session) {
        SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
        if (config.getSumPayMoney() < 0) {
            return 0;
        }
        double sumMoney = this.payLogServiceDao.getSumMoneyByType_0();
        int count = 0;
        for (int checkMoney = config.getTempSumPayMoney() > 0 ? config.getTempSumPayMoney() : config.getSumPayMoney();
             sumMoney + money > checkMoney; count++) {
            checkMoney += config.getSumPayMoney();
        }
        return count;
    }

    public int checkSumExpiry(int gameGold, int type, IoSession session) {
        SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
        if (config.getSumExpiryMoney() < 0) {
            return 0;
        }
        double money = 0.0D;
        if (type == 0) {
            money = MyUtil.doubleDivideCalculation(gameGold * config.getPayScale(), 100.0D);
        } else {
            money = MyUtil.doubleDivideCalculation(gameGold * config.getPromoterPayScale(), 100.0D);
        }
        double sumMoney = this.payLogServiceDao.getSumMoneyByType_1();
        int count = 0;
        for (int checkMoney = config.getTempSumExpiryMoney() > 0 ? config.getTempSumExpiryMoney() : config.getSumExpiryMoney();
             sumMoney + money > checkMoney; count++) {
            checkMoney += config.getSumExpiryMoney();
        }
        return count;
    }

    public int checkOneSumExpiry(int userId, int gameGold, IoSession session) {
        SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
        if (config.getUserSumMoney() < 0) {
            return 0;
        }
        double money = MyUtil.doubleDivideCalculation(gameGold * config.getPayScale(), 100.0D);
        double sumMoney = this.payLogServiceDao.getSumMoneyByUserId_0(userId);
        int count = 0;
        for (int checkMoney = config.getTempUserSumMoney() > 0 ? config.getTempUserSumMoney() : config.getUserSumMoney();
             sumMoney + money > checkMoney; count++) {
            checkMoney += config.getUserSumMoney();
        }
        return count;
    }

    public void addUserLevel(int id) {
        this.userServiceDao.addUserLevel(id);
    }

    public Map<String, Object> getUserList(int type, Pager pager, IoSession session) {
        Map<String, Object> map = new HashMap<>();
        String orgOrderBy = pager.getOrderBy();
        String orgOrder = pager.getOrder();
        if (StringUtils.isBlank(pager.getOrderBy())) {
            pager.setOrderBy("payMoney desc,expiryNum desc,username");
        } else {
            List<String> orderby = new ArrayList<>();
            orderby.add("payMoney");
            orderby.add("expiryNum");
            orderby.add("username");
            orderby.remove(pager.getOrderBy());
            StringBuilder sb = new StringBuilder(pager.getOrderBy() + " " + pager.getOrder());
            for (String o : orderby) {
                sb.append("," + o + " " + pager.getOrder());
            }
            pager.setOrderBy(sb.toString());
            pager.setOrder(null);
        }
        String hql = null;
        if (type == 0) {
            hql = "from User where promoterId = 0 and type=0";
        } else if (type == 1) {
            hql = "from User where promoterId != 0";
        } else {
            hql = "from User where type = 1";
        }
        if (!GameParameterAssist.bH) {
            hql = "from User";
        }
        Object sumGold = this.userServiceDao.q_CreateSql("select sum(gameGold) " + hql, new Object[0]).uniqueResult();
        pager = this.userServiceDao.q_CreateSqlsPager(hql, pager, new Object[0]);
        pager.setOrderBy(orgOrderBy);
        pager.setOrder(orgOrder);
        Object[] os = pager.getList();
        Object[] array;
        int length = (array = os).length;
        for (int i = 0; i < length; i++) {
            Object o2 = array[i];
            User user = (User) o2;
            user.setDisplayStatus(0);
            if (user.getStatus() == 1) {
                user.setDisplayStatus(1);
            } else if (user.getOverflow() == 1) {
                user.setDisplayStatus(2);
            } else if (user.getShutupStatus() != 0) {
                user.setDisplayStatus(3);
            } else if (user.getStatus() == 2) {
                user.setDisplayStatus(4);
            } else if (user.getStatus() == 3) {
                user.setDisplayStatus(5);
            }
        }
        map.put("pager", pager);
        map.put("gold", sumGold == null ? Integer.valueOf(0) : sumGold);
        map.put("number", this.userServiceDao.getQuantity());
        return map;
    }

    public Map<String, Object> getUserManage(int type, Pager pager, IoSession session) {
        Map<String, Object> map = new HashMap<>();
        String hql = null;
        if (type == 0) {
            hql = "from User where promoterId = 0 and type=0";
        } else if (type == 1) {
            hql = "from User where promoterId != 0";
        } else if (type == 2) {
            hql = "from User where type = 1";
        } else {
            hql = "from User";
        }
        if (!GameParameterAssist.bH) {
            hql = "from User";
        }
        Object sumGold = this.userServiceDao.q_CreateSql("select sum(gameGold) " + hql, new Object[0]).uniqueResult();
        pager = this.userServiceDao.q_CreateSqlsPager(hql, pager, new Object[0]);
        Object[] os = pager.getList();
        Object[] array;
        int length = (array = os).length;
        for (int i = 0; i < length; i++) {
            Object o = array[i];
            User user = (User) o;
            this.userServiceDao.evict(user);
            if (resultInt(session) == 0) {
                user.setQuestion((String) GameParameterAssist.bM.get(user.getQuestion()));
            } else {
                user.setQuestion((String) GameParameterAssist.bL.get(user.getQuestion()));
            }
            user.setDisplayStatus(0);
            if (user.getStatus() == 1) {
                user.setDisplayStatus(1);
            } else if (user.getOverflow() == 1) {
                user.setDisplayStatus(2);
            } else if (user.getShutupStatus() != 0) {
                user.setDisplayStatus(3);
            } else if (user.getStatus() == 2) {
                user.setDisplayStatus(4);
            } else if (user.getStatus() == 3) {
                user.setDisplayStatus(5);
            }
        }
        map.put("pager", pager);
        map.put("gold", sumGold == null ? Integer.valueOf(0) : sumGold);
        map.put("number", this.userServiceDao.getQuantity());
        return map;
    }

    public Map<String, Object> lockUser(int id, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        this.userServiceDao.updateStatus(id, 1);
        User user = (User) this.userServiceDao.getById(id);
        Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        AdminLog adminLog = new AdminLog(admin.getUsername(), "对会员“" + user.getUsername() + "”进行了“封号”操作", 0, admin.getType(), "Frozen the member which ID is " + user.getUsername());
        this.adminLogServiceDao.addAdminLog(adminLog);
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        quitToLogin(user.getId(), 2);
        return result;
    }

    public Map<String, Object> unlockUser(int id, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) this.userServiceDao.getById(id);
        this.userServiceDao.updateStatus(id, 0);
        UserWarning userWarning = this.userWarningServiceDao.q_CreateSqlFilter("from UserWarning where userId=? ", new Object[]{id});
        if (userWarning != null) {
            UserWarningBak userWarningBak = new UserWarningBak();
            userWarningBak.setUserId(userWarning.getUserId());
            userWarningBak.setYaGold(userWarning.getYaGold());
            userWarningBak.setDeGold(userWarning.getDeGold());
            userWarningBak.setGiveGold(userWarning.getGiveGold());
            userWarningBak.setDeductGold(userWarning.getDeductGold());
            userWarningBak.setPayCount(userWarning.getPayCount());
            userWarningBak.setExpiryCount(userWarning.getExpiryCount());
            userWarningBak.setGameGold(userWarning.getGameGold());
            userWarningBak.setDate(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
            boolean b = this.userWarningBakServiceDao.updateBak(userWarningBak);
        }
        GameParameterAssist.aJ.remove(id);
        Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        AdminLog adminLog = new AdminLog(admin.getUsername(), "对会员“" + user.getUsername() + "”进行了“解封”操作", 0, admin.getType(), "Thaw the member which ID is " + user.getUsername());
        this.adminLogServiceDao.addAdminLog(adminLog);
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        return result;
    }

    public Map<String, Object> deleteUser(int id, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) this.userServiceDao.getById(id);
        this.computerOrderServiceDao.deleteById(id);
        this.userServiceDao.deleteById(id);
        deleteWarning(id);
        Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        AdminLog adminLog = new AdminLog(admin.getUsername(), "对会员“" + user.getUsername() + "”进行了“删号”操作", 0, admin.getType(), "Delete the member which ID is " + user.getUsername());
        this.adminLogServiceDao.addAdminLog(adminLog);
        quitToLogin(id, 3);
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        return result;
    }

    public void deleteWarning(int nUserId) {
        this.userWarningServiceDao.deleteByNUserId(nUserId);
        this.userWarningBakServiceDao.deleteByNUserId(nUserId);
    }

    public Map<String, Object> minusGameGold(int id, int minusGold, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) this.userServiceDao.getById(id);
        if (minusGold < 0) {
            logger.error("less than zero minusGameGold:" + minusGold);
            result.put("success", Boolean.FALSE);
            result.put("message", MyUtil.getProperties(resultInt(session), "systemError"));
            result.put("newGold", user.getGameGold());
            return result;
        }
        int count = this.userServiceDao.updateGameById(id, -minusGold, 0);
        if (count <= 0) {
            user = (User) this.userServiceDao.getById(id);
            result.put("success", Boolean.FALSE);
            result.put("message", MyUtil.getProperties(resultInt(session), "systemError"));
            result.put("newGold", user.getGameGold());
            return result;
        }
        SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
        Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        PayLog paylog = new PayLog();
        paylog.setAdmin(admin.getUsername());
        paylog.setAuthority(admin.getType());
        paylog.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
        paylog.setGold(minusGold);
        paylog.setType(2);
        paylog.setUsername(user.getUsername());
        paylog.setMoney(MyUtil.doubleDivideCalculation(minusGold * config.getPayScale(), 100.0D));
        User user2 = (User) this.userServiceDao.getById(id);
        paylog.setGameGold(user2.getGameGold() + user2.getExpiryNum());
        this.payLogServiceDao.save(paylog);
        int nFlag = this.userWarningServiceDao.updateDeductInfoByUid(user.getId(), minusGold);
        if (nFlag == -1) {
            result.put("success", Boolean.FALSE);
            result.put("message", MyUtil.getProperties(resultInt(session), "systemError"));
            result.put("newGold", user.getGameGold());
            return result;
        }
        AdminLog adminLog = new AdminLog(admin.getUsername(), "对会员“" + user.getUsername() + "”进行了“扣除游戏币”操作，扣除了" + minusGold + "游戏币", 0, admin.getType(), "The operation of deduct coins has been operated for the member which ID is " + user.getUsername() + " ,a total of " + minusGold + " coins");
        this.adminLogServiceDao.addAdminLog(adminLog);
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        user = (User) this.userServiceDao.getById(id);
        result.put("newGold", user.getGameGold());
        pubGoldNotice(user);
        if ((user.getOverflow() == 1) && ((config.getMoneyOverrun() == -1) || (MyUtil.goldExchange(user.getGameGold(), config.getPayScale()) < config.getMoneyOverrun()))) {
            this.userServiceDao.updateOverflow(id, 0);
            if (GameParameterAssist.ba.containsKey(id)) {
                MessageSend.q.notifyAllOperating(new StorageMethodEntity(GameParameterAssist.ba.get(id), "unOverflow", new Object[0]));
            }
        }
        return result;
    }

    public Map<String, Object> awardGameGold(int id, int gameGold, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        this.userServiceDao.updateGameById(id, gameGold, 0);
        User user = (User) this.userServiceDao.getById(id);
        UserAward ua = new UserAward();
        ua.setUserId(id);
        ua.setUsername(user.getUsername());
        ua.setGold(gameGold);
        ua.setStatus(0);
        ua.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
        ua.setAdmin(admin.getUsername());
        ua.setAuthority(admin.getType());
        this.userWarningServiceDao.updateGiveInfoByUid(user.getId(), gameGold);
        AdminLog adminLog = new AdminLog(admin.getUsername(), "对会员“" + user.getUsername() + "”进行了“赠送游戏币”操作，赠送了" + gameGold + "游戏币", 0, admin.getType(), "The operation of present coins has been operated for the member which ID is " + user.getUsername() + " ,a total of " + gameGold + " coins");
        this.adminLogServiceDao.addAdminLog(adminLog);
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
        if (user.getParentId() != 0) {
            //给上级返佣
            int score = new BigDecimal(config.getRechargeRebate()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(gameGold)).intValue();
            if (score > 0) {
                User user2 = (User) this.userServiceDao.getById(user.getParentId());
                this.userServiceDao.updateGameById(user2.getId(), score, 0);
                UserAward ua1 = new UserAward();
                ua1.setUserId(user2.getId());
                ua1.setUsername(user2.getUsername());
                ua1.setGold(score);
                ua1.setStatus(0);
                ua1.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
                ua1.setAdmin("系统充值返佣");
                ua1.setAuthority(admin.getType());
                this.userAwardServiceDao.save(ua1);
            }
            if(user.getRechargeActivity() == 0){
                RechargeActivity rechargeActivity = rechargeActivityServiceDao.q_CreateSqlFilter("from RechargeActivity where user_id=?", new Object[]{user.getParentId()});
                //给上级 活动 随机金额1-20
                if (rechargeActivity != null && rechargeActivity.getAmount().compareTo(new BigDecimal(1000)) < 0) {
                    double rand = 1 + Math.random() * (config.getRandomAmount()-1);
                    if (rechargeActivity.getAmount().add(new BigDecimal(rand).setScale(2,BigDecimal.ROUND_DOWN)).compareTo(new BigDecimal(1000)) > 0) {
                        rechargeActivity.setAmount(new BigDecimal(1000));
                    } else {
                        rechargeActivity.setAmount(rechargeActivity.getAmount().add(new BigDecimal(rand).setScale(2,BigDecimal.ROUND_DOWN)));
                    }
                    rechargeActivityServiceDao.update(rechargeActivity);
                    this.userServiceDao.updateRechargeActivityById(user.getId(),1);
                }
            }
        }
        boolean isOverflow = false;
        double userMoney = MyUtil.goldExchange(user.getGameGold(), config.getPayScale());
        if ((config.getMoneyOverrun() != -1) && (userMoney >= config.getMoneyOverrun()) && (user.getOverflow() == 0)) {
            this.userServiceDao.updateOverflow(id, 1);
            isOverflow = true;
        }
        if (GameParameterAssist.ba.containsKey(id)) {
            ua.setStatus(1);
            MessageSend.q.notifyAllOperating(new StorageMethodEntity(GameParameterAssist.ba.get(id), "userAward", new Object[]{gameGold}));
        }
        for (GameTypeSession gameTypeSession : SessionUtils.getSessionByUserId(user.getId())) {
            for (IoSession s : gameTypeSession.getSessionSet()) {
                AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(s, "manageService/userAward", new Object[]{id, gameGold}));
            }
        }
        this.userAwardServiceDao.save(ua);
        if (isOverflow) {
            logger.info("awardGameGold isOverflow userId:" + id);
            pubOverflowNotice(id);
        }
        logger.info("awardGameGold begin pubGoldNotice userId:" + user.getId());
        pubGoldNotice(user);
        return result;
    }

    public Map<String, Object> updateIndentityInfo(int id, String question, String answer, String phone, String card, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) this.userServiceDao.getById(id);
        StringBuilder content = new StringBuilder("对会员“" + user.getUsername() + "”进行了“身份信息修改”操作");
        StringBuilder contentEn = new StringBuilder();
        if (!user.getQuestion().equals(question)) {
            content.append("，修改安全问题为“" + question + "”");
            contentEn.append("The security question of the member which ID is " + user.getUsername() + " has been changed to " + question + ",");
        }
        if (!user.getAnswer().equals(answer)) {
            content.append("，修改问题答案为“" + answer + "”");
            contentEn.append("The security question answer of the member which ID is " + user.getUsername() + " has been changed to " + answer + ",");
        }
        if (!user.getPhone().equals(phone)) {
            content.append("，修改手机号为“" + phone + "”");
            contentEn.append("The phone number of the member which ID is " + user.getUsername() + " has been changed to " + phone + ",");
        }
        if (!user.getCard().equals(card)) {
            content.append("，修改身份证号为“" + card + "”");
            contentEn.append("The ID number of the member which ID is " + user.getUsername() + " has been changed to " + card);
        }
        this.userServiceDao.updateQuestionInfoById(id, question, answer, phone, card);
        if (contentEn.length() > 0) {
            Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
            Admin admin = (Admin) this.adminServiceDao.getById(adminId);
            AdminLog adminLog = new AdminLog(admin.getUsername(), content.toString(), 0, admin.getType(), contentEn.toString());
            this.adminLogServiceDao.addAdminLog(adminLog);
        }
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        return result;
    }

    public Map<String, Object> resetUserPassword(int id, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) this.userServiceDao.getById(id);
        this.userServiceDao.updatePasswordById(id, DigestUtils.md5Hex("666666"));
        Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        AdminLog adminLog = new AdminLog(admin.getUsername(), "对会员“" + user.getUsername() + "”进行了“重置密码”操作", 0, admin.getType(), "Reset the password of the member which ID is " + user.getUsername());
        this.adminLogServiceDao.addAdminLog(adminLog);
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        quitToLogin(id, 5);
        return result;
    }

    public static void quitToLogin(int userId, int type) {
        if (GameParameterAssist.ba.containsKey(userId)) {
            IoSession session = GameParameterAssist.ba.remove(userId);
            Map<String, Object> map = new HashMap<>();
            map.put("type", type);
            MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "quitToLogin", new Object[]{map}));
            session.removeAttribute("username");
            session.removeAttribute("id");
        }
        GameParameterAssist.aR.remove(userId);
        for (GameTypeSession gameTypeSession : SessionUtils.getSessionByUserId(userId)) {
            if (type == 4) {
                UserParticipateRecord.addUserGameMap(userId, gameTypeSession.getGameType());
            }
            for (IoSession session : gameTypeSession.getSessionSet()) {
                AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(session, "manageService/quitToLogin", new Object[]{userId, type}));
            }
        }
    }

    private boolean isGameLogin(int userId) {
        if (GameParameterAssist.bh.containsKey(userId)) {
            return Boolean.TRUE;
        }
        if (GameParameterAssist.bi.containsKey(userId)) {
            return Boolean.TRUE;
        }
        if (GameParameterAssist.bj.containsKey(userId)) {
            return Boolean.TRUE;
        }
        if (GameParameterAssist.bk.containsKey(userId)) {
            return Boolean.TRUE;
        }
        if (GameParameterAssist.bl.containsKey(userId)) {
            return Boolean.TRUE;
        }
        if (GameParameterAssist.aN.containsKey(userId)) {
            return Boolean.TRUE;
        }
        if (GameParameterAssist.aP.containsKey(userId)) {
            return Boolean.TRUE;
        }
        if (GameParameterAssist.bs.containsKey(userId)) {
            return Boolean.TRUE;
        }
        if (GameParameterAssist.fishKingBi.containsKey(userId)) {
            return Boolean.TRUE;
        }
        if (GameParameterAssist.thounsandFishGameType2.containsKey(userId)) {
            return Boolean.TRUE;
        }
        if (GameParameterAssist.likuiFishUserId.containsKey(userId)) {
            return Boolean.TRUE;
        }
        if (GameParameterAssist.goldenFishUserId.containsKey(userId)) {
            return Boolean.TRUE;
        }
        if (GameParameterAssist.tgUserId.containsKey(userId)) {
            return Boolean.TRUE;
        }
        if (GameParameterAssist.goldSharkUserId.containsKey(userId)) {
            return Boolean.TRUE;
        }
        if (GameParameterAssist.bcbmUserId.containsKey(userId)) {
            return Boolean.TRUE;
        }
        if (GameParameterAssist.lhdUserId.containsKey(userId)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    public Map<String, Object> shutupUser(int id, int type, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) this.userServiceDao.getById(id);
        this.userShutupServiceDao.deleteByUid(id);
        this.userServiceDao.updateShutupStatus(id, type);
        String content = null;
        String contentEn = null;
        if (type == 0) {
            notifyAllOperatingByContainsKey(id, false);
        } else {
            UserShutup us = new UserShutup();
            us.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
            us.setType(type);
            us.setUserId(id);
            if (type == 1) {
                content = "对玩家“" + user.getUsername() + "”进行了“禁言”操作，设置为 20 分钟";
                contentEn = "The operation of gag has been operated for the member which ID is " + user.getUsername() + " ,time is 20 minutes";
                us.setDeleteDatetime(System.currentTimeMillis() + 1200000L);
            } else if (type == 2) {
                content = "对玩家“" + user.getUsername() + "”进行了“禁言”操作，设置为 6 小时";
                contentEn = "The operation of gag has been operated for the member which ID is " + user.getUsername() + " ,time is 6 hours";
                us.setDeleteDatetime(System.currentTimeMillis() + 21600000L);
            } else if (type == 3) {
                content = "对玩家“" + user.getUsername() + "”进行了“禁言”操作，设置为 1 天";
                contentEn = "The operation of gag has been operated for the member which ID is " + user.getUsername() + " ,time is 1 days";
                us.setDeleteDatetime(System.currentTimeMillis() + 86400000L);
            }
            this.userShutupServiceDao.save(us);
            notifyAllOperatingByContainsKey(id, true);
        }
        if (content != null) {
            Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
            Admin admin = (Admin) this.adminServiceDao.getById(adminId);
            AdminLog adminLog = new AdminLog(admin.getUsername(), content, 0, admin.getType(), contentEn);
            this.adminLogServiceDao.addAdminLog(adminLog);
        }
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        return result;
    }

    private void notifyAllOperatingByContainsKey(int userId, boolean isShutup) {
        for (GameTypeSession gameTypeSession : SessionUtils.getSessionByUserId(userId)) {
            for (IoSession session : gameTypeSession.getSessionSet()) {
                AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(session, "manageService/userShutup", new Object[]{userId, isShutup}));
            }
        }
    }

    public Map<String, Object> searchUser(String keyword, int type, int userType, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        StringBuilder hql = new StringBuilder("from User");
        StringBuilder str = new StringBuilder();
        StringBuilder strEn = new StringBuilder();
        StringBuilder strEn2 = new StringBuilder();
        if (!GameParameterAssist.bH) {
            userType = 3;
        }
        if (userType == 0) {
            hql.append(" where promoterId=0 and type=0");
            str.append("直属会员");
            strEn.append("direct member");
        } else if (userType == 1) {
            hql.append(" where promoterId!=0");
            str.append("非直属会员");
            strEn.append("indirect member");
        } else if (userType == 2) {
            hql.append(" where type=1");
            str.append("游客");
            strEn.append("guest");
        } else {
            hql.append(" where 1=1");
            str.append("所有");
        }
        if (type == 0) {
            hql.append(" and username like ?");
            str.append("账号" + keyword);
            strEn2.append("ID is " + keyword);
        } else if (type == 1) {
            hql.append(" and phone like ?");
            str.append("手机号" + keyword);
            strEn2.append("phone number is " + keyword);
        } else {
            hql.append(" and card like ?");
            str.append("身份证号" + keyword);
            strEn2.append("ID number is " + keyword);
        }
        hql.append(" order by payMoney desc,expiryNum desc,username");
        long sumGold = 0L;
        List<User> users = this.userServiceDao.q_CreateSqlList(hql.toString(), new Object[]{"%" + keyword + "%"});
        for (User user : users) {
            this.userServiceDao.evict(user);
            if (resultInt(session) == 0) {
                user.setQuestion((String) GameParameterAssist.bM.get(user.getQuestion()));
            } else {
                user.setQuestion((String) GameParameterAssist.bL.get(user.getQuestion()));
            }
            sumGold += user.getGameGold();
            user.setDisplayStatus(0);
            if (user.getStatus() == 1) {
                user.setDisplayStatus(1);
            } else if (user.getOverflow() == 1) {
                user.setDisplayStatus(2);
            } else if (user.getShutupStatus() != 0) {
                user.setDisplayStatus(3);
            } else if (user.getStatus() == 2) {
                user.setDisplayStatus(4);
            } else if (user.getStatus() == 3) {
                user.setDisplayStatus(5);
            }
        }
        result.put("gold", Long.valueOf(sumGold));
        result.put("number", Integer.valueOf(this.userServiceDao.getQuantity()));
        result.put("results", users.toArray(new User[0]));
        return result;
    }

    public Map<String, Object> getUserInfo(int id, IoSession session) {
        Map result = new HashMap<>();
        User user = (User) this.userServiceDao.getById(Integer.valueOf(id));
        if (user != null) {
            int count = this.computerOrderServiceDao.q_CreateSqlInt("select count(*) from ComputerOrder where user.id=? and status=0", new Object[]{Integer.valueOf(user.getId())});
            if (count > 0) {
                user.setBorrow(1);
            } else {
                user.setBorrow(0);
            }
            result.put("success", Boolean.TRUE);
            result.put("message", "");
            result.put("user", user);
        } else {
            result.put("success", Boolean.FALSE);
            result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "systemError"));
            result.put("user", user);
        }
        return result;
    }

    public Map<String, Object> changeUserControl(int id, int controlType, int controlExpire, int maxGold, int fishControlValue, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        userServiceDao.updateUserControl(id, controlType, controlExpire, maxGold, fishControlValue);
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        List<GameTypeEnums> gameTypeEnumsList = Arrays.asList(GameTypeEnums.GT_1, GameTypeEnums.GT_3, GameTypeEnums.GT_4, GameTypeEnums.GT_20, GameTypeEnums.GT_37, GameTypeEnums.GT_92);
        for (GameTypeEnums gameTypeEnums : gameTypeEnumsList) {
            Set<IoSession> sessions = SessionUtils.getSessionByGameType(gameTypeEnums.getType());
            for (IoSession ioSession : sessions) {
                AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(ioSession, "manageService/refreshUserControl", new Object[]{id, controlType, controlExpire, maxGold, fishControlValue}));
            }
        }
        return result;
    }

    public Map<String, Object> changeUserLevel(int id, int level, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        userServiceDao.updateUserLevel(id, level);
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        return result;
    }

    public void gameLoadAddress(int gameType, String versionCode, IoSession session) {
        logger.info("...gameLoadAddress:" + gameType + " is " + versionCode);
        Map result = new HashMap<>();
        result.put("gameType", Integer.valueOf(gameType));
        Version version = this.versionServiceDao.getByType(gameType);
        if ((version != null) && (versionCode.equals("-2"))) {
            int nUserId = ((Integer) session.getAttribute("id"));
            UserParticipateRecord.updateStatus(nUserId, 100);
            MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "gameLoadAddress", new Object[]{result}));
            logger.info("1.gameLoadAddress..." + nUserId + " status is Hall");
            if (UserParticipateRecord.checkUserId_1(nUserId) == -1) {
                UserParticipateRecord.updateStatus(nUserId, 100);
                logger.info("2.gameLoadAddress change " + nUserId + " Hall status TO INGAME");
            }
        } else if (((version != null) && (versionCode.equals("-1"))) || ((version != null) && (!version.getVersionCode().equals(versionCode)))) {
            result.put("haveNewVersionIDFlag", Boolean.TRUE);
            result.put("versionCode", version.getVersionCode());
            result.put("downloadWindows", version.getDownloadWindows());
            result.put("downloadAndroid", version.getDownloadAndroid());
            MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "gameLoadAddress", new Object[]{result}));
        } else {
            result.put("haveNewVersionIDFlag", Boolean.FALSE);
            if (version == null) {
                result.put("downloadWindows", "");
                result.put("downloadAndroid", "");
                MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "gameLoadAddress", new Object[]{result}));
            } else {
                result.put("downloadWindows", version.getDownloadWindows());
                result.put("downloadAndroid", version.getDownloadAndroid());
                MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "gameLoadAddress", new Object[]{result}));
            }
            int nUserId = ((Integer) session.getAttribute("id"));
            if (UserParticipateRecord.checkUserId_1(nUserId) == -1) {
                UserParticipateRecord.updateStatus(nUserId, 100);
            }
        }
    }

    public int[] checkGameVersions(String[] versions, IoSession session) {
        System.out.println(versions.toString());
        int[] nCheckList = new int[versions.length];
        for (int i = 0; i < nCheckList.length; i++) {
            if (versions[i] != null) {
                String version = versions[i];
                if (version.equals(this.versionServiceDao.getByType(i + 1).getVersionCode())) {
                    nCheckList[i] = 0;
                } else {
                    nCheckList[i] = 1;
                }
            }
        }
        System.out.println(nCheckList.toString());
        System.out.println(nCheckList);
        return nCheckList;
    }

    public Map<String, Object> tellServerUserPassword(int type, String password, IoSession session) {
        Map result = new HashMap<>();
        result.put("nType", Integer.valueOf(type));
        int userId = Integer.parseInt(session.getAttribute("id").toString());
        User user = (User) this.userServiceDao.getById(Integer.valueOf(userId));
        Map manage = new HashMap<>();
        IoSession waitSession = null;
        for (Map.Entry entry : GameParameterAssist.bw.entrySet()) {
            if (((Map) entry.getValue()).containsKey(Integer.valueOf(userId))) {
                waitSession = (IoSession) entry.getKey();
            }
        }
        if (user.getPassword().equals(DigestUtils.md5Hex(password))) {
            manage.put("success", Boolean.TRUE);
            manage.put("type", Integer.valueOf(type));
            manage.put("message", "");
            result.put("bFlag", Boolean.TRUE);
            if ((user.getPromoterId() != 0) && (waitSession != null)) {
                int gold = ((Integer) GameParameterAssist.bC.get(Integer.valueOf(userId)));
                int count = this.userServiceDao.updateGameById(Integer.valueOf(userId), -gold, 0);
                int nFlag = this.userWarningServiceDao.updateExpiryCountByUid(userId, gold);
                if (nFlag == -1) {
                    result.put("bFlag", Boolean.FALSE);
                    return result;
                }
                if (count > 0) {
                    this.promoterServiceDao1.addGold(user.getPromoterId(), gold);
                    SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
                    double money = MyUtil.doubleDivideCalculation(gold * config.getPayScale(), 100.0D);
                    PayLog payLog = new PayLog(userId, user.getUsername(), MyUtil.dateFormatYMD_HMS_Sting(new Date()), money, gold, user.getPromoterName(), 1, 0, 0, "", 0, user.getPromoterId(), user.getGameGold() + user.getExpiryNum());
                    this.payLogServiceDao.save(payLog);
                    String content = "对会员" + user.getUsername() + "进行了“兑奖”操作，金额为" + money + "元";
                    String contentEn = "Exchange " + gold + " coins for the member which ID is " + user.getUsername();
                    this.promoterLogServiceDao.save_3(user.getPromoterId(), content, contentEn);
                    String message = MyUtil.sessionAttributeFormat(waitSession, "expiryForUser", new Object[]{user.getUsername(), Integer.valueOf(gold), Double.valueOf(money)});
                    manage.put("message", message);
                    user = (User) this.userServiceDao.getById(Integer.valueOf(userId));
                    pubGoldNotice(user);
                    if (user.getOverflow() == 1) {
                        double userMoney = MyUtil.goldExchange(user.getGameGold(), config.getPayScale());
                        Promoter promoter = (Promoter) this.promoterServiceDao1.getById(Integer.valueOf(user.getPromoterId()));
                        if (userMoney < promoter.getChildrenUserOver()) {
                            this.userServiceDao.updateOverflow(userId, 0);
                            MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "unOverflow", new Object[0]));
                        }
                    }
                } else {
                    manage.put("success", Boolean.FALSE);
                    manage.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(waitSession)), "notGold"));
                }
            }
        } else {
            if (waitSession != null) {
                manage.put("success", Boolean.FALSE);
                manage.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(waitSession)), "userInputPwdError"));
                manage.put("type", Integer.valueOf(type));
            }
            result.put("bFlag", Boolean.FALSE);
        }
        if (waitSession != null) {
            AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(waitSession, "getGameInput", new Object[]{manage}));
            GameParameterAssist.bw.remove(waitSession);
            GameParameterAssist.bC.remove(Integer.valueOf(userId));
        }
        return result;
    }

    public int getShutupType(int id, IoSession session) {
        UserShutup us = this.userShutupServiceDao.getByUid(id);
        return us == null ? 0 : us.getType();
    }

    public int[] countNewRegist(String startDate, String endDate) {
        int selfCount = this.userServiceDao.q_CreateSqlInt("select count(*) from User where promoterId = 0 and registDate>=? and registDate<?", new Object[]{startDate, endDate});
        int children = this.userServiceDao.q_CreateSqlInt("select count(*) from User where promoterId != 0 and registDate>=? and registDate<?", new Object[]{startDate, endDate});
        int[] cs = {selfCount, children};
        return cs;
    }

    public int[] countDailyActive(String startDate, String endDate) {
        int selfCount = this.userServiceDao.q_CreateSqlInt("select count(*) from User where promoterId=0 and loginDate>=? and loginDate<?", new Object[]{startDate, endDate});
        int childrenCount = this.userServiceDao.q_CreateSqlInt("select count(*) from User where promoterId!=0 and loginDate>=? and loginDate<?", new Object[]{startDate, endDate});
        int[] cs = {selfCount, childrenCount};
        return cs;
    }

    public void updateOverflow(int userId, int i) {
        this.userServiceDao.updateOverflow(userId, i);
    }

    public void heart(IoSession session) {
        GameParameterAssist.bg.put(session, Long.valueOf(System.currentTimeMillis()));
        MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "heart", new Object[0]));
    }

    public void updateShutupStatus(int userId, int status) {
        this.userServiceDao.updateShutupStatus(userId, status);
    }

    public void updateNoActive(String date) {
        this.userServiceDao.updateNoActive(date);
    }

    public Map<String, Object> exCharge(int gold, String remark, String password, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        int userId = ((Integer) session.getAttribute("id"));
        synchronized (PayApplyService.expiryLock) {
            User user = (User) this.userServiceDao.getById(userId);
            if (gold <= 0) {
                result.put("success", Boolean.FALSE);
                result.put("messageStatus", 0);
                return result;
            }
            if (!user.getPassword().equals(DigestUtils.md5Hex(password))) {
                result.put("success", Boolean.FALSE);
                result.put("messageStatus", 1);
                return result;
            }
            if (user.getGameGold() < gold) {
                result.put("success", Boolean.FALSE);
                result.put("messageStatus", 0);
                return result;
            }
            SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
            if (config.getExpiry() == -1) {
                result.put("success", Boolean.FALSE);
                result.put("messageStatus", 2);
                return result;
            }
            if (user.getExpiryNum() > 0) {
                result.put("success", Boolean.FALSE);
                result.put("messageStatus", 3);
                return result;
            }
            if ((remark != null) && (remark.length() > 200)) {
                remark = remark.substring(0, 200);
            }
            this.userServiceDao.updateExpiryNum(userId, gold, remark);
            PayApply payApply = new PayApply(MyUtil.dateFormatYMD_HMS_Sting(new Date()), gold, userId, remark, PayApply.PayApplyState.PENDING, System.currentTimeMillis() + config.getExpiry() * 60000, 0, 1, false);
            this.payApplyServiceDao.save(payApply);
            this.payApplyServiceDao.getAllPayApply().add(payApply);
            if (user.getPromoterId() == 0) {
                Map<String, Object> countMap = getUserPayCount();
                for (IoSession as : GameParameterAssist.be.values()) {
                    AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(as, "userPayCount", new Object[]{countMap}));
                }
            } else {
                IoSession s = GameParameterAssist.bx.get(user.getPromoterId());
                if (s != null) {
                    this.l.promoterAppUserPayCount(s, user.getPromoterId());
                }
            }
            result.put("success", Boolean.TRUE);
            user = (User) this.userServiceDao.getById(userId);
            MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "newGameGold", new Object[]{user.getGameGold()}));
            if (user.getOverflow() == 1) {
                double userMoney = MyUtil.goldExchange(user.getGameGold(), config.getPayScale());
                int overMoney = 0;
                if (user.getPromoterId() != 0) {
                    Promoter promoter = (Promoter) this.promoterServiceDao1.getById(user.getPromoterId());
                    overMoney = promoter.getChildrenUserOver();
                } else {
                    overMoney = config.getMoneyOverrun();
                }
                if (userMoney < overMoney) {
                    this.userServiceDao.updateOverflow(userId, 0);
                    if (GameParameterAssist.ba.containsKey(userId)) {
                        MessageSend.q.notifyAllOperating(new StorageMethodEntity(GameParameterAssist.ba.get(userId), "unOverflow", new Object[0]));
                    }
                }
            }
            return result;
        }
    }

    public Map<String, Object> recharge(int payMoney, String remark, IoSession session) {
        Map result = new HashMap<>();
        int userId = ((Integer) session.getAttribute("id"));
        synchronized (PayApplyService.expiryLock) {
            User user = (User) this.userServiceDao.getById(Integer.valueOf(userId));
            if (payMoney <= 0) {
                result.put("success", Boolean.FALSE);
                result.put("messageStatus", Integer.valueOf(0));
                Map map = result;
                return map;
            }
            SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
            if (config.getExpiry() == -1) {
                result.put("success", Boolean.FALSE);
                result.put("messageStatus", Integer.valueOf(0));
                Map map2 = result;
                return map2;
            }
            if (user.getPayMoney() > 0) {
                result.put("success", Boolean.FALSE);
                result.put("messageStatus", Integer.valueOf(1));
                Map map3 = result;
                return map3;
            }
            if ((remark != null) && (remark.length() > 200)) {
                remark = remark.substring(0, 200);
            }
            this.userServiceDao.updatePayMoney(userId, payMoney);
            PayApply payApply = new PayApply(MyUtil.dateFormatYMD_HMS_Sting(new Date()), payMoney, userId, remark, PayApply.PayApplyState.PENDING, System.currentTimeMillis() + config.getExpiry() * 60000, 0, 0, false);
            this.payApplyServiceDao.save(payApply);
            this.payApplyServiceDao.getAllPayApply().add(payApply);
            if (user.getPromoterId() == 0) {
                Map countMap = getUserPayCount();
                for (IoSession as : GameParameterAssist.be.values()) {
                    AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(as, "userPayCount", new Object[]{countMap}));
                }
            } else {
                IoSession s = (IoSession) GameParameterAssist.bx.get(Integer.valueOf(user.getPromoterId()));
                if (s != null) {
                    this.l.promoterAppUserPayCount(s, user.getPromoterId());
                }
            }
        }
        result.put("success", Boolean.TRUE);
        return result;
    }

    public Map<String, Object> getUserPayCount() {
        Map result = new HashMap<>();
        int payCount = this.userServiceDao.q_CreateSqlInt("select count(*) from User where payMoney > 0 and promoterId = 0", new Object[0]);
        int expiryCount = this.userServiceDao.q_CreateSqlInt("select count(*) from User where expiryNum > 0 and promoterId = 0", new Object[0]);
        result.put("payCount", Integer.valueOf(payCount));
        result.put("expiryCount", Integer.valueOf(expiryCount));
        return result;
    }

    public void addGameGold(int userId, int gameGold) {
        this.userServiceDao.updateGameById(Integer.valueOf(userId), gameGold, 0);
    }

    public void updateExpiryNum(int userId, int expiryNum) {
        this.userServiceDao.updateExpiryNum(userId, expiryNum);
    }

    public void updatePayMoney(int userId, int payMoney) {
        this.userServiceDao.updatePayMoney(userId, payMoney);
    }

    public static void recharge(IoSession session) {
        Map result = new HashMap<>();
        result.put("success", Boolean.FALSE);
        result.put("messageStatus", Integer.valueOf(0));
        MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "recharge", new Object[]{result}));
    }

    public static void excharge(IoSession session) {
        Map result = new HashMap<>();
        result.put("success", Boolean.FALSE);
        result.put("messageStatus", Integer.valueOf(2));
        MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "exCharge", new Object[]{result}));
    }

    public static void chargeNotice(IoSession session, PayApply payApply) {
        Map result = new HashMap<>();
        result.put("time", payApply.getDatetime());
        result.put("gameGold", Integer.valueOf(payApply.getAmmount()));
        result.put("type", Integer.valueOf(payApply.getType()));
        MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "chargeNotice", new Object[]{result}));
    }

    public Map<String, Object> getUserPlayLog(int userId, String startDate, String endDate, Pager pager, IoSession session) {
        Map map = new HashMap<>();
        endDate = MyUtil.DateByDayCalendar(endDate, 1);
        String hql1 = "from UserTenMinScore where userId=? and startTime>=? and endTime<=?";
        if (pager.getOrderBy() == "") {
            pager = this.userServiceDao.q_CreateSqlsPager(String.valueOf("from UserTenMinScore where userId=? and startTime>=? and endTime<=?") + " order by startTime desc", pager, new Object[]{Integer.valueOf(userId), startDate, endDate});
        } else {
            if (pager.getOrderBy().endsWith("datetime")) {
                pager.setOrderBy("startTime");
            }
            if (pager.getOrderBy().endsWith("userGain")) {
                pager.setOrderBy("yaGold");
            }
            if (pager.getOrderBy().endsWith("userTotalValue")) {
                pager.setOrderBy(" user_total_gold");
            }
            pager = this.userServiceDao.q_CreateSqlsPager("from UserTenMinScore where userId=? and startTime>=? and endTime<=?", pager, new Object[]{Integer.valueOf(userId), startDate, endDate});
        }
        List datas = new ArrayList();
        Object[] list;
        int length = (list = pager.getList()).length;
        for (int i = 0; i < length; i++) {
            Object o = list[i];
            UserTenMinScore utms = (UserTenMinScore) o;
            Map data = new HashMap<>();
            String endTime = utms.getEndTime().substring(utms.getEndTime().indexOf(" ") + 1, utms.getEndTime().length());
            String datetime = String.valueOf(utms.getStartTime()) + "-" + endTime;
            data.put("datetime", datetime);
            data.put("username", utms.getUsername());
            data.put("yaGold", Integer.valueOf(utms.getYaGold()));
            data.put("deGold", Integer.valueOf(utms.getDeGold()));
            data.put("userGain", Integer.valueOf(utms.getYaGold() - utms.getDeGold()));
            data.put("userGold", Integer.valueOf(utms.getUserGold()));
            data.put("userScore", Integer.valueOf(utms.getUserScore()));
            data.put("userTotalValue", Integer.valueOf(utms.getUserTotalGold()));
            datas.add(data);
        }
        pager.setList(datas.toArray());
        map.put("pager", pager);
        long lastYaGold = 0L;
        long lastDeGold = 0L;
        long lastTotalGain = 0L;
        String hql2 = "";
        hql2 = "select ifnull(sum(ya_gold),0) ,ifnull(sum(de_gold),0) from user_ten_min_score where user_id=" + userId + " and start_time>=? and end_time<=? ";
        List<Object[]> log = this.userServiceDao.returnList_3(hql2, startDate, endDate);
        for (Object[] o2 : log) {
            lastYaGold = Long.parseLong(o2[0].toString());
            lastDeGold = Long.parseLong(o2[1].toString());
            lastTotalGain = lastYaGold - lastDeGold;
        }
        map.put("lastTotalPlay", Long.valueOf(lastYaGold));
        map.put("lastTotalGet", Long.valueOf(lastDeGold));
        map.put("lastTotalGain", Long.valueOf(lastTotalGain));
        return map;
    }

    public void deleteUserPlayLog(String date) {
        this.userServiceDao.deleteByDate(date);
    }

    public List<User> getNeedAddGoldRobotUserList(String robotPromoter) {
        return userServiceDao.q_CreateSqlList("from User where promoterName=? and gameGold=0 and gameScore=0", new Object[]{robotPromoter});
    }

    public List<User> getUserList() {
        return this.userServiceDao.getUsers();
    }

    public void addUserWarning(UserWarning userWarning) {
        this.userWarningServiceDao.save(userWarning);
    }

    public void addUserWarningBak(UserWarningBak userWarningBak) {
        this.userWarningBakServiceDao.save(userWarningBak);
    }

    public List<UserWarning> getUserWarning() {
        return this.userWarningServiceDao.getUserWarnings();
    }

    public List<UserWarningBak> getUserWarningBak() {
        return this.userWarningBakServiceDao.getUserWarningBaks();
    }

    public void add(String date) {
        this.userServiceDao.deleteByDate(date);
    }

    public boolean checkWarning(int userId) {
        UserWarning userWarning = new UserWarning();
        userWarning = this.userWarningServiceDao.getByUid(userId);
        UserWarningBak userWarningBak = new UserWarningBak();
        userWarningBak = this.userWarningBakServiceDao.getByUId(userId);
        SystemConfig systemConfig = new SystemConfig();
        int payScale = (int) MyUtil.doubleMultiplyCalculation(Double.valueOf(systemConfig.getPayScale()).doubleValue(), 100.0D);
        long lExpiryCount = userWarning.getExpiryCount() - userWarningBak.getExpiryCount();
        long lPayCount = userWarning.getPayCount() - userWarningBak.getPayCount();
        long lGameGold = userWarning.getGameGold() - userWarningBak.getGameGold();
        long lDeductGold = userWarning.getDeductGold() - userWarningBak.getDeductGold();
        long lGiveGold = userWarning.getGiveGold() - userWarningBak.getGiveGold();
        long lDeGold = (long) (userWarning.getDeGold() - userWarningBak.getDeGold());
        long lYaGold = (long) (userWarning.getYaGold() - userWarningBak.getYaGold());
        long lLeft = lExpiryCount - lPayCount + lGameGold + lDeductGold - lGiveGold;
        long lRight = lDeGold - lYaGold + 500L;
        long division;
        if ((lExpiryCount == 0L) || (payScale == 0)) {
            division = 0L;
        } else {
            division = lExpiryCount / payScale;
        }
        if (lLeft > lRight) {
            Map warningResult = new HashMap<>();
            warningResult.put("status", Integer.valueOf(1));
            warningResult.put("expiryGold", Long.valueOf(lLeft - lRight));
            GameParameterAssist.aJ.add(Integer.valueOf(userId));
            logger.info("1Current" + userWarning.toString() + ";" + lLeft + "," + lRight);
            this.userServiceDao.updateWarningStatus(userId, (int) (lLeft - lRight));
            this.userServiceDao.updateStatus(userId, 1);
            quitToLogin(userId, 2);
            return false;
        }
        if ((division > 50000L) && (lExpiryCount + lGameGold > 10L * lPayCount + 100L)) {
            Map warningResult = new HashMap<>();
            warningResult.put("status", Integer.valueOf(2));
            warningResult.put("expiryGold", Long.valueOf(userWarning.getExpiryCount()));
            warningResult.put("payGold", Long.valueOf(userWarning.getPayCount()));
            warningResult.put("yaGold", Double.valueOf(userWarning.getYaGold()));
            warningResult.put("deGold", Double.valueOf(userWarning.getDeGold()));
            GameParameterAssist.aJ.add(Integer.valueOf(userId));
            logger.info("2Current" + userWarning.toString() + ";" + lLeft + "," + lRight);
            this.userServiceDao.updateWarningStatus(userId, -1);
            this.userServiceDao.updateStatus(userId, 1);
            quitToLogin(userId, 2);
            return false;
        }
        if ((division > 100000L) && (lExpiryCount + lGameGold > 5L * lPayCount + 100L)) {
            Map warningResult = new HashMap<>();
            warningResult.put("status", Integer.valueOf(2));
            warningResult.put("expiryGold", Long.valueOf(userWarning.getExpiryCount()));
            warningResult.put("payGold", Long.valueOf(userWarning.getPayCount()));
            warningResult.put("yaGold", Double.valueOf(userWarning.getYaGold()));
            warningResult.put("deGold", Double.valueOf(userWarning.getDeGold()));
            GameParameterAssist.aJ.add(Integer.valueOf(userId));
            logger.info("1Current" + userWarning.toString() + ";" + lLeft + "," + lRight);
            this.userServiceDao.updateWarningStatus(userId, -1);
            this.userServiceDao.updateStatus(userId, 1);
            quitToLogin(userId, 2);
            return false;
        }
        return true;
    }

    public List<UserWarning> getAllOnlineUser() {
        List userWarningList = new ArrayList();
        UserWarning userWarning = new UserWarning();
        for (Integer nUserId : GameParameterAssist.aF) {
            userWarning = this.userWarningServiceDao.getByUid(nUserId);
            userWarningList.add(userWarning);
        }
        return userWarningList;
    }

    public Map<String, Object> cancelExpiryPwd(int userId, IoSession session) {
        User user = (User) this.userServiceDao.getById(Integer.valueOf(userId));
        if (user == null) {
            Map localMap1 = resultFormat(false, MyUtil.getSessionAttribute(session, "accountError"));
        } else {
            Object map = new HashMap<>();
            map = (Map) GameParameterAssist.aI.get(Integer.valueOf(userId));
            IoSession se = null;
            int type = 0;
            int parentId = 0;
            if (map != null) {
                Set<Entry> set = ((Map) map).entrySet();
                for (Map.Entry e : set) {
                    type = ((Integer) e.getValue());
                    parentId = ((Integer) e.getKey());
                }
            }
            if (map != null) {
                if (type == 1) {
                    se = (IoSession) GameParameterAssist.bx.get(Integer.valueOf(parentId));
                    if (se != null) {
                        Map manage = new HashMap<>();
                        manage.put("success", Boolean.FALSE);
                        manage.put("message", MyUtil.getSessionAttribute(se, "memberCancelledExchange"));
                        manage.put("type", Integer.valueOf(0));
                        AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(se, "getGameInput", new Object[]{manage}));
                        GameParameterAssist.bw.remove(se);
                        GameParameterAssist.aI.remove(Integer.valueOf(userId));
                    }
                } else if (type == 0) {
                    se = (IoSession) GameParameterAssist.be.get(Integer.valueOf(parentId));
                    if (se != null) {
                        Map manage = new HashMap<>();
                        manage.put("success", Boolean.FALSE);
                        manage.put("message", MyUtil.getSessionAttribute(se, "memberCancelledExchange"));
                        manage.put("type", Integer.valueOf(0));
                        AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(se, "getGameInput", new Object[]{manage}));
                        GameParameterAssist.bw.remove(se);
                        GameParameterAssist.aI.remove(Integer.valueOf(userId));
                    }
                }
            }
        }
        Map result = resultFormat(true, "");
        return result;
    }

    public UserWarning getLastUser() {
        return this.userWarningServiceDao.getLastUser();
    }

    public List<User> getLastUserList(int nLastUserId) {
        return this.userServiceDao.getUserByIdLtNLastUserId(nLastUserId);
    }

    public User[] getTreasureList(IoSession session) {
        List tops = this.userServiceDao.getUsersOrderByGameGold();
        return (User[]) tops.toArray(new User[0]);
    }

    public User[] getLevelList(IoSession session) {
        List tops = this.userServiceDao.getUsersOrderByLevel();
        return (User[]) tops.toArray(new User[0]);
    }

    public List<User> getActivityUserList() {
        List users = new ArrayList();
        String hql = "from User where promoterId = 0 and type=0";
        users = this.userServiceDao.q_CreateSqlList("from User where promoterId = 0 and type=0", new Object[0]);
        return users;
    }

    public void updateStatus(int id, int status) {
        this.userServiceDao.updateStatus(id, status);
    }

    public Map<String, Object> dealException(int id, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) this.userServiceDao.getById(Integer.valueOf(id));
        this.userServiceDao.updateWarningStatus(id, 0);
        this.userServiceDao.updateStatus(id, 0);
        UserWarning userWarning = (UserWarning) this.userWarningServiceDao.q_CreateSqlFilter("from UserWarning where userId=? ", new Object[]{Integer.valueOf(id)});
        UserWarningBak userWarningBak = new UserWarningBak();
        userWarningBak.setUserId(userWarning.getUserId());
        userWarningBak.setYaGold(userWarning.getYaGold());
        userWarningBak.setDeGold(userWarning.getDeGold());
        userWarningBak.setGiveGold(userWarning.getGiveGold());
        userWarningBak.setDeductGold(userWarning.getDeductGold());
        userWarningBak.setPayCount(userWarning.getPayCount());
        userWarningBak.setExpiryCount(userWarning.getExpiryCount());
        userWarningBak.setGameGold(userWarning.getGameGold());
        userWarningBak.setDate(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
        this.userWarningBakServiceDao.updateBak(userWarningBak);
        GameParameterAssist.aJ.remove(Integer.valueOf(id));
        Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        AdminLog adminLog = new AdminLog(admin.getUsername(), "对会员“" + user.getUsername() + "”进行了“解除异常”操作", 0, admin.getType(), "Thaw the member which ID is " + user.getUsername());
        this.adminLogServiceDao.addAdminLog(adminLog);
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        return result;
    }

    public long getClearingScore() {
        String hql = "from User where gameScore!=0";
        List<User> users = this.userServiceDao.q_CreateSqlList("from User where gameScore!=0", new Object[0]);
        long nGold = 0L;
        for (User user : users) {
            int nExchange = getDeskExchange(user);
            int nClearningGold = 0;
            if (user.getGameScore() > 0) {
                nClearningGold = user.getGameScore() / nExchange;
                if (user.getGameScore() % nExchange != 0) {
                    int odd = user.getGameScore() % nExchange;
                    double per = odd / nExchange;
                    int range = (int) per * 100;
                    Random random = new Random();
                    if (random.nextInt(100) < range) {
                        nClearningGold++;
                    }
                }
            }
            nGold += nClearningGold;
        }
        return nGold;
    }

    public int getDeskExchange(User user) {
        Integer deskId = user.getLastDeskId();
        Integer nGameType = user.getLastGame();
        int exchange = 0;
        if (user.getLastGame() == GameTypeEnums.GT_0.getType()) {
            Desk desk = this.deskServiceDao.getDesk(deskId);
            if (desk == null) {
                exchange = this.recordDeleteDeskServiceDao.getRecordDeleteDesk(nGameType, deskId);
            } else {
                exchange = desk.getExchange();
            }
        } else if (user.getLastGame() == GameTypeEnums.GT_1.getType()) {
            FishDesk desk2 = (FishDesk) this.fishDeskServiceDao.getById(deskId);
            if (desk2 == null) {
                exchange = this.recordDeleteDeskServiceDao.getRecordDeleteDesk(nGameType, deskId);
            } else {
                exchange = desk2.getExchange();
            }
        } else if (user.getLastGame() == GameTypeEnums.GT_2.getType()) {
            CardDesk desk3 = (CardDesk) this.cardDeskServiceDao.getById(deskId);
            if (desk3 == null) {
                exchange = this.recordDeleteDeskServiceDao.getRecordDeleteDesk(nGameType, deskId);
            } else {
                exchange = desk3.getExchange();
            }
        } else if (user.getLastGame() == GameTypeEnums.GT_3.getType()) {
            BulletFishDesk desk4 = this.bulletFishDeskServiceDao.getBulletDesk(deskId);
            if (desk4 == null) {
                exchange = this.recordDeleteDeskServiceDao.getRecordDeleteDesk(nGameType, deskId);
            } else {
                exchange = desk4.getExchange();
            }
        } else if (user.getLastGame() == GameTypeEnums.GT_4.getType()) {
            MermaidDesk desk5 = this.mermaidDeskServiceDao.getMermaidDesk(deskId);
            if (desk5 == null) {
                exchange = this.recordDeleteDeskServiceDao.getRecordDeleteDesk(nGameType, deskId);
            } else {
                exchange = desk5.getExchange();
            }
        } else if (user.getLastGame() == GameTypeEnums.GT_5.getType()) {
            LackDesk desk6 = (LackDesk) this.lackDeskServiceDao.getById(deskId);
            if (desk6 == null) {
                exchange = this.recordDeleteDeskServiceDao.getRecordDeleteDesk(nGameType, deskId);
            }
            exchange = desk6.getExchange();
        } else if (user.getLastGame() == GameTypeEnums.GT_6.getType()) {
            JoyDesk joyDesk = (JoyDesk) this.joyDeskServiceDao.getById(deskId);
            if (joyDesk == null) {
                exchange = this.recordDeleteDeskServiceDao.getRecordDeleteDesk(nGameType, deskId);
            } else {
                exchange = joyDesk.getExchange();
            }
        } else if (user.getLastGame() == GameTypeEnums.GT_7.getType()) {
            WaterDesk waterDesk = (WaterDesk) waterDeskServiceDao.getById(deskId);
            if (waterDesk == null) {
                exchange = this.recordDeleteDeskServiceDao.getRecordDeleteDesk(nGameType, deskId);
            } else {
                exchange = waterDesk.getExchange();
            }
        } else if (user.getLastGame() == GameTypeEnums.GT_9.getType()) {
            ThousandFishDesk thousandFishDesk = (ThousandFishDesk) this.thousandFishDeskDao.getById(deskId);
            if (thousandFishDesk == null) {
                exchange = this.recordDeleteDeskServiceDao.getRecordDeleteDesk(nGameType, deskId);
            } else {
                exchange = thousandFishDesk.getExchange();
            }
        } else if (user.getLastGame() == GameTypeEnums.GT_11.getType()) {
            FishKingDesk fishKingDesk = (FishKingDesk) this.fishKingDB.getById(deskId);
            if (fishKingDesk == null) {
                exchange = this.recordDeleteDeskServiceDao.getRecordDeleteDesk(nGameType, deskId);
            } else {
                exchange = fishKingDesk.getExchange();
            }
        } else if (user.getLastGame() == GameTypeEnums.GT_20.getType()) {
            LiKuiFishDesk liKuiFishDesk = (LiKuiFishDesk) this.liKuiFishDeskDao.getById(deskId);
            if (liKuiFishDesk == null) {
                exchange = this.recordDeleteDeskServiceDao.getRecordDeleteDesk(nGameType, deskId);
            } else {
                exchange = liKuiFishDesk.getExchange();
            }
        } else if (user.getLastGame() == GameTypeEnums.GT_37.getType()) {
            GoldenCicadaFishDesk goldenCicadaFishDesk = (GoldenCicadaFishDesk) this.goldenCicadaFishDeskDao.getById(deskId);
            if (goldenCicadaFishDesk == null) {
                exchange = this.recordDeleteDeskServiceDao.getRecordDeleteDesk(nGameType, deskId);
            } else {
                exchange = goldenCicadaFishDesk.getExchange();
            }
        } else if (user.getLastGame() == GameTypeEnums.GT_42.getType()) {
            GoldSharkDesk desk = goldSharkDeskDao.getDesk(deskId);
            if (desk == null) {
                exchange = this.recordDeleteDeskServiceDao.getRecordDeleteDesk(nGameType, deskId);
            } else {
                exchange = desk.getExchange();
            }
        } else if (user.getLastGame() == GameTypeEnums.GT_52.getType()) {
            BcbmDesk bcbmDesk = bcbmDeskDao.getBcbmDesk(deskId);
            if (bcbmDesk == null) {
                exchange = this.recordDeleteDeskServiceDao.getRecordDeleteDesk(nGameType, deskId);
            } else {
                exchange = bcbmDesk.getExchange();
            }
        } else if (user.getLastGame() == GameTypeEnums.GT_92.getType()) {
            TianGongDesk tianGongDesk = tianGongDeskDao.getTianGongDesk(deskId);
            if (tianGongDesk == null) {
                exchange = this.recordDeleteDeskServiceDao.getRecordDeleteDesk(nGameType, deskId);
            } else {
                exchange = tianGongDesk.getExchange();
            }
        } else if (user.getLastGame() == GameTypeEnums.GT_103.getType()) {
            DragonTigerDesk desk = dragonTigerDeskDao.getDesk(deskId);
            if (desk == null) {
                exchange = this.recordDeleteDeskServiceDao.getRecordDeleteDesk(nGameType, deskId);
            } else {
                exchange = desk.getExchange();
            }
        }
        return exchange;
    }
    /*public Map<String, Object> visitorLogin(String paramString1, String paramString2, IoSession paramIoSession) {
        Map<String, Object> result = new HashMap<>();
        int i = 0;
        try {
            User localUser = new User();
            localUser.setUsername(paramString1);
            localUser.setNickname(paramString2);
            localUser.setPhotoId(3);
            localUser.setLevel(1);
            localUser.setType(1);
            localUser.setPassword("123456");
            logger.info("user:" + localUser.getUsername());
            SystemConfig localSystemConfig = this.systemConfigServiceDao.getSystemConfig();
            if (localSystemConfig.getRegistVerify() == 1) {
                logger.info("游客禁止登录，注册验证开启");
                result.put("success", Boolean.TRUE);
                result.put("isLogin", Boolean.FALSE);
                result.put("msgCode", -2);
                return result;
            }
            int j = this.userServiceDao.q_CreateSqlInt("select count(*) from User where username=?", new Object[]{localUser.getUsername()});
            if (j > 0) {
                i = 1;
            }
            if (i == 0) {
                logger.info("未注册游客:" + localUser.getUsername());
                if ((StringUtils.isBlank(localUser.getPromoterName())) || (localUser.getPromoterName().equals("admin"))) {
                    localUser.setPromoterId(0);
                    localUser.setPromoterName("admin");
                } else {
                    Promoter localPromoter = this.promoterServiceDao1.q_CreateSqlFilter("from Promoter where username=?", new Object[]{localUser.getPromoterName()});
                    if (localPromoter == null) {
                        result.put("success", Boolean.FALSE);
                        result.put("messageStatus", 2);
                        return result;
                    }
                    localUser.setPromoterId(localPromoter.getId());
                }
                localUser.setPassword(DigestUtils.md5Hex(localUser.getPassword()));
                if (localSystemConfig.getRegistVerify() == 1) {
                    logger.info("zhuceyanzheng kai");
                    int k = this.userRegistLogServiceDao.getQuantityByUsername(localUser.getUsername());
                    logger.info("applyReigstCount:" + k);
                    if (k > 0) {
                        result.put("success", Boolean.FALSE);
                        result.put("messageStatus", 1);
                        return result;
                    }
                    String str = ((InetSocketAddress) paramIoSession.getRemoteAddress()).getAddress().getHostAddress();
                    UserRegistLog localUserRegistLog = UserRegistLog.create(localUser.getUsername(), localUser.getNickname(), localUser.getPromoterName(), localUser.getPromoterId(), localUser.getPhone(), str, localUser.getPassword());
                    boolean bool = this.userRegistLogService.addRegistApply(localUserRegistLog);
                    if (bool) {
                        result.put("success", Boolean.TRUE);
                        result.put("messageStatus", -2);
                    } else {
                        result.put("success", Boolean.FALSE);
                        result.put("messageStatus", -3);
                    }
                    return result;
                }
                regist(localUser);
                this.userServiceDao.q_CreateSqlInt("select count(*) from User where username=?", new Object[]{localUser.getUsername()});
            }
        } catch (Exception localException) {
            logger.error("visitorLoginLog:", localException);
            result.put("success", Boolean.FALSE);
            result.put("messageStatus", -1);
            AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(paramIoSession, "register", new Object[]{result}));
            throw new RuntimeException();
        }
        logger.info("游客:" + paramString1 + " 登录!");
        result = userLogin(paramString1, "123456", "8.3.2", paramIoSession);
        return result;
    }*/
    public Map<String, Object> reLogin(String username, String password, int language, IoSession session) {
        Version version = this.versionServiceDao.getByType(0);
        logger.info("用户重连：" + username + ",version=" + version.getVersionCode());
        return userLogin(username, password, language, version.getVersionCode(), session);
    }

    public Map<String, Object> getShareLog(int userId, String startDate, String endDate, Pager pager, IoSession
            session) {
        return new HashMap<>();
    }

    public Map<String, Object> getGiftLog(int userId, String startDate, String endDate, Pager pager, IoSession
            session) {
        return new HashMap<>();
    }

    public Map<String, Object> getLotteryCoinExchangeLog(int userId, String startDate, String endDate, Pager
            pager, IoSession session) {
        return new HashMap<>();
    }

    public Map<String, Object> setSafeBoxPwd(String safeBoxPwd, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        String username = (String) session.getAttribute("username");
        if (username == null) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 13);
            return result;
        }
        User user = this.userServiceDao.q_CreateSqlFilter("from User where username=?", new Object[]{username});
        if (user == null) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 13);
            return result;
        }
        logger.info("setSafeBoxPwd：" + username + "," + safeBoxPwd);
        if (user.getStatus() != 0) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 6);
            return result;
        }
        SystemConfig config = this.systemConfigServiceDao.q_CreateSqlFilter("from SystemConfig", new Object[0]);
        if ((config != null) && (config.getGameStatus() == 1) && (user.getType() != 2)) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 7);
            return result;
        }
        if (!Pattern.compile("\\d{6}").matcher(safeBoxPwd).matches()) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 14);
            return result;
        }
        this.userServiceDao.updateSafeBox(user.getId(), 1);
        this.userServiceDao.updateSafeBoxPwd(user.getId(), safeBoxPwd);
        result.put("success", Boolean.TRUE);
        result.put("msgCode", 0);
        return result;
    }

    public Map<String, Object> checkSafeBoxPwd(String safeBoxPwd, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        String username = (String) session.getAttribute("username");
        if (username == null) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 13);
            return result;
        }
        User user = this.userServiceDao.q_CreateSqlFilter("from User where username=?", new Object[]{username});
        if (user == null) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 13);
            return result;
        }
        logger.info("checkSafeBoxPwd：" + username + "," + safeBoxPwd);
        if (user.getStatus() != 0) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 6);
            return result;
        }
        SystemConfig config = this.systemConfigServiceDao.q_CreateSqlFilter("from SystemConfig", new Object[0]);
        if ((config != null) && (config.getGameStatus() == 1) && (user.getType() != 2)) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 7);
            return result;
        }
        if (!Pattern.compile("\\d{6}").matcher(safeBoxPwd).matches()) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 3);
            return result;
        }
        if (user.getSecurity() != Integer.parseInt(safeBoxPwd)) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 3);
            return result;
        }
        Map<String, Object> safeBox = new HashMap<>();
        safeBox.put("gameGold", user.getBoxGameGold());
        safeBox.put("lottery", user.getBoxLottery());
        result.put("safeBox", safeBox);
        result.put("success", Boolean.TRUE);
        result.put("msgCode", 0);
        return result;
    }

    public Map<String, Object> deposit(int gameGold, int payMode, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        String username = (String) session.getAttribute("username");
        if (username == null) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 13);
            return result;
        }
        User user = this.userServiceDao.q_CreateSqlFilter("from User where username=?", new Object[]{username});
        if (user == null) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 13);
            return result;
        }
        logger.info("deposit：" + username + "," + gameGold + "," + payMode);
        if (user.getStatus() != 0) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 6);
            return result;
        }
        SystemConfig config = this.systemConfigServiceDao.q_CreateSqlFilter("from SystemConfig", new Object[0]);
        if ((config != null) && (config.getGameStatus() == 1) && (user.getType() != 2)) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 7);
            return result;
        }
        logger.info("存入" + gameGold + "游戏币");
        if ((gameGold <= 0) || (user.getGameGold() < gameGold)) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 12);
            return result;
        }
        int count = this.userServiceDao.addBoxGameGold(user.getId(), gameGold);
        logger.info("保险柜增加游戏币 userId:" + user.getId() + ",gameGold:" + gameGold);
        this.userServiceDao.updateGameById(user.getId(), -gameGold, 0);
        logger.info("用户减少游戏币  userId:" + user.getId() + ",gameGold:" + -gameGold);
        if (count > 0) {
            User user2 = (User) this.userServiceDao.getById(user.getId());
            MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "gameGold", new Object[]{user2.getGameGold()}));
            result.put("success", Boolean.TRUE);
            result.put("msgCode", 0);
            result.put("boxGameGold", user2.getBoxGameGold());
            result.put("boxLottery", user2.getBoxLottery());
            result.put("gameGold", user2.getGameGold());
            result.put("lottery", user2.getLottery());
        }
        return result;
    }

    public Map<String, Object> extract(int gameGold, int payMode, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        String username = (String) session.getAttribute("username");
        if (username == null) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 13);
            return result;
        }
        User user = this.userServiceDao.q_CreateSqlFilter("from User where username=?", new Object[]{username});
        if (user == null) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 13);
            return result;
        }
        logger.info("deposit：" + username + "," + gameGold + "," + payMode);
        if (user.getStatus() != 0) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 6);
            return result;
        }
        SystemConfig config = this.systemConfigServiceDao.q_CreateSqlFilter("from SystemConfig", new Object[0]);
        if ((config != null) && (config.getGameStatus() == 1) && (user.getType() != 2)) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 7);
            return result;
        }
        logger.info("取出 " + gameGold + "游戏币");
        if ((gameGold <= 0) || (user.getBoxGameGold() < gameGold)) {
            result.put("success", Boolean.FALSE);
            result.put("msgCode", 12);
            return result;
        }
        int count = this.userServiceDao.addBoxGameGold(user.getId(), -gameGold);
        logger.info("保险柜减少游戏币 userId:" + user.getId() + ",gameGold:" + -gameGold);
        this.userServiceDao.updateGameById(user.getId(), gameGold, 0);
        logger.info("用户增加游戏币  userId:" + user.getId() + ",gameGold:" + gameGold);
        if (count > 0) {
            User user2 = (User) this.userServiceDao.getById(user.getId());
            MessageSend.q.notifyAllOperating(new StorageMethodEntity(session, "gameGold", new Object[]{user2.getGameGold()}));
            result.put("success", Boolean.TRUE);
            result.put("msgCode", 0);
            result.put("boxGameGold", user2.getBoxGameGold());
            result.put("boxLottery", user2.getBoxLottery());
            result.put("gameGold", user2.getGameGold());
            result.put("lottery", user2.getLottery());
        }
        return result;
    }

    public Map<String, Object> getAllActivity(IoSession session) {
        Map<String, Object> result = new HashMap<>();
        result.put("activity", activityServiceDao.getActivityList());
        return result;
    }

    public Map<String, Object> getCustomerServiceUrl(IoSession session) {
        int userId = ((Integer) session.getAttribute("id"));
        SystemConfig systemConfig = systemConfigServiceDao.getSystemConfig();
        User user = (User) this.userServiceDao.getById(userId);
        Promoter promoter = this.promoterServiceDao1.q_CreateSqlFilter("from Promoter where username=?", new Object[]{user.getPromoterName()});
        if (promoter != null && StringUtils.isNotBlank(promoter.getKefu())) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", Boolean.TRUE);
            result.put("url", String.format(promoter.getKefu(), userId, user.getPromoterName()));
            return result;
        }
        Map<String, Object> result = new HashMap<>();
        result.put("success", Boolean.TRUE);
        result.put("url", systemConfig != null ? systemConfig.getServiceUrl() : "");
        return result;
    }

    public String getIncomeRankList(IoSession session) {
        List<IncomeRank> list = incomeRankDao.q_CreateSqlList("from IncomeRank order by income desc", new Object[0]);
        int size = list.size();
        for (int i = 0; i < 20 - size; i++) {
            list.add(new IncomeRank());
        }
        return JSONArray.fromObject(list).toString();
    }

    public Map<String, Object> saveIncomeRankList(String incomeRankList, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            JSONArray jsonArray = JSONArray.fromObject(incomeRankList);
            List<IncomeRank> list = JSONArray.toList(jsonArray, IncomeRank.class);
            for (IncomeRank incomeRank : list) {
                if (StringUtils.isNotBlank(incomeRank.getUsername()) && incomeRank.getIncome() > 0) {
                    incomeRankDao.saveOrUpdate(incomeRank);
                }
            }
            result.put("success", Boolean.TRUE);
        } catch (Exception e) {
            result.put("success", Boolean.FALSE);
            result.put("message", "更新异常");
        }
        return result;
    }

    public Map<String, Object> getRechargeActivityInfo(int userId, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            RechargeActivity rechargeActivity = rechargeActivityServiceDao.q_CreateSqlFilter("from RechargeActivity where user_id=?", new Object[]{userId});
            if (rechargeActivity == null) {
                rechargeActivity = new RechargeActivity();
                rechargeActivity.setAmount(new BigDecimal(192.56));
                rechargeActivity.setUserId(userId);
                rechargeActivity.setBalance(BigDecimal.ZERO);
                rechargeActivity.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
                this.rechargeActivityServiceDao.save(rechargeActivity);
            }
            SystemConfig config = this.systemConfigServiceDao.q_CreateSqlFilter("from SystemConfig", new Object[0]);
            result.put("amount", rechargeActivity.getAmount().doubleValue());
            result.put("balance", rechargeActivity.getBalance().doubleValue());
            result.put("shareAddress", config.getShareAddress());
            result.put("success", Boolean.TRUE);
        } catch (Exception e) {
            result.put("success", Boolean.FALSE);
            result.put("message", "更新异常");
        }
        return result;
    }

    public Map<String, Object> withdrawalToGameBalance(int userId, int amount, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            RechargeActivity rechargeActivity = rechargeActivityServiceDao.q_CreateSqlFilter("from RechargeActivity where user_id=?", new Object[]{userId});
            BigDecimal money = rechargeActivity.getAmount().subtract(rechargeActivity.getBalance());
            if (money.compareTo(new BigDecimal(amount)) >= 0) {
                User tempUser3 = userServiceDao.q_CreateSqlFilter("from User where id=?", new Object[]{userId});
                userServiceDao.updateGameById(userId, amount, 0);
                rechargeActivity.setBalance(rechargeActivity.getBalance().add(new BigDecimal(amount)));
                rechargeActivityServiceDao.update(rechargeActivity);
                UserAward ua = new UserAward();
                ua.setUserId(userId);
                ua.setUsername(tempUser3.getUsername());
                ua.setGold(amount);
                ua.setStatus(0);
                ua.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
                ua.setAdmin("活动提现");
                ua.setAuthority(1);
                userWarningServiceDao.updateGiveInfoByUid(tempUser3.getId(), amount);
                AdminLog adminLog = new AdminLog("活动提现", "对会员“" + tempUser3.getUsername() + "”进行了“赠送游戏币”操作，赠送了" + amount + "游戏币", 0, 1, "The operation of present coins has been operated for the member which ID is " + tempUser3.getUsername() + " ,a total of " + amount + " coins");
                adminLogServiceDao.addAdminLog(adminLog);
                userAwardServiceDao.save(ua);
                result.put("amount", rechargeActivity.getAmount().doubleValue());
                result.put("balance", rechargeActivity.getBalance().doubleValue());
                result.put("success", Boolean.TRUE);
            } else {
                result.put("message", "条件不满足或已经提现");
                result.put("success", Boolean.FALSE);
            }
        } catch (Exception e) {
            result.put("success", Boolean.FALSE);
            result.put("message", "更新异常");
        }
        return result;
    }
    public Map<String, Object> subUserList(int userId, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        List<User> userList = new ArrayList<>();
        try {
            userList = this.userServiceDao.q_CreateSqlList("from User where parentId=?  order by id desc", new Object[]{userId});
            result.put("userList", userList);
            result.put("success", Boolean.TRUE);
        } catch (Exception e) {
            result.put("success", Boolean.FALSE);
            result.put("message", "更新异常");
        }
        return result;
    }
    public Map<String, Object> subUserStatistics(int userId, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        result.put("user1", 0);
        result.put("user2", 0);
        result.put("user3", 0);
        try {
            User tempUser = userServiceDao.q_CreateSqlFilter("from User where id=?", new Object[]{userId});
            if(tempUser.getParentId() != 0){
                User  tempUser1 = userServiceDao.q_CreateSqlFilter("from User where id=?", new Object[]{tempUser.getParentId()});
                if(tempUser1.getParentId()!=0){
                    User  tempUser2 = userServiceDao.q_CreateSqlFilter("from User where id=?", new Object[]{tempUser1.getParentId()});
                    if(tempUser2.getParentId()!=0){
                        User  tempUser3 = userServiceDao.q_CreateSqlFilter("from User where id=?", new Object[]{tempUser2.getParentId()});
                        result.put("user1", tempUser3.getSonNUm());
                        result.put("user2", tempUser2.getSonNUm());
                        result.put("user3", tempUser1.getSonNUm());
                    }else {
                        result.put("user1", tempUser2.getSonNUm());
                        result.put("user2", tempUser1.getSonNUm());
                    }
                }else {
                    result.put("user1", tempUser1.getSonNUm());
                }
            }
            SystemConfig config = this.systemConfigServiceDao.q_CreateSqlFilter("from SystemConfig", new Object[0]);
            result.put("user", tempUser);
            result.put("shareAddress", config.getShareAddress());
            result.put("success", Boolean.TRUE);
        } catch (Exception e) {
            result.put("success", Boolean.FALSE);
            result.put("message", "更新异常");
        }
        return result;
    }

    public Map<String, Object> subUserAllList(int userId, int level,IoSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
           // User tempUser = userServiceDao.q_CreateSqlFilter("from User where id=?", new Object[]{userId});
            List<User> list = new ArrayList<>();
            List<User>  userList = userServiceDao.q_CreateSqlList("from User where parentId=?", new Object[]{userId});
            if(level == 1){ //一级会员
                list = userList;
            }else if(level == 2) {
                if(!CollectionUtils.isEmpty(userList)){
                    List<Integer> ids = new ArrayList<>();
                    for (User u:userList) {
                        ids.add(u.getId());
                    }
                    logger.info("asdasdsadasdasdasd22222222："+ids.size());
                    String listStr = StringUtils.join(ids.toArray(),",");
                    if(!CollectionUtils.isEmpty(ids)){
                        String sql = "from User where parentId in (" + listStr + ") ";
                        List<User>  userList2 = userServiceDao.q_CreateSqlList(sql, new Object[]{0});
                        list = userList2;
                    }

                }
            }else if(level == 3)  {
                if(!CollectionUtils.isEmpty(userList)){
                    List<Integer> ids = new ArrayList<>();
                    for (User u:userList) {
                        ids.add(u.getId());
                    }
                    String listStr = StringUtils.join(ids.toArray(),",");
                    if(!CollectionUtils.isEmpty(ids)){
                        String sql = "from User where parentId in (" + listStr + ") ";
                        List<User>  userList2 = userServiceDao.q_CreateSqlList(sql, new Object[]{0});
                        if(!CollectionUtils.isEmpty(userList2)){
                            List<String> ids2 = new ArrayList<>();
                            for (User u:userList) {
                                ids2.add(u.getId()+"");
                            }
                            String listStr2 = StringUtils.join(ids2.toArray(),",");
                            List<User>  userList3 = userServiceDao.q_CreateSqlList("from User where parentId in (" + listStr2 + ") ", new Object[]{0});
                            list = userList3;
                        }
                    }
                }
            }
            result.put("userList", list);
            result.put("success", Boolean.TRUE);
        } catch (Exception e) {
            result.put("success", Boolean.FALSE);
            result.put("message", "查询异常");
            logger.error(e.getMessage());
        }
        return result;
    }

    public Map<String, Object> receiveAmount(int userId, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            User user = (User) this.userServiceDao.getById(userId);
            if(user.getUnincome() > 0){
                this.userServiceDao.updateGameById(user.getId(), user.getUnincome(), 0);
                UserAward ua = new UserAward();
                ua.setUserId(user.getId());
                ua.setUsername(user.getUsername());
                ua.setGold(user.getUnincome());
                ua.setStatus(0);
                ua.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
                ua.setAdmin("系统返佣(领取)");
                ua.setAuthority(1);
                userWarningServiceDao.updateGiveInfoByUid(user.getId(), user.getUnincome());
                AdminLog adminLog = new AdminLog("系统返佣", "对会员“" + user.getUsername() + "”进行了“赠送游戏币”操作，赠送了" + user.getUnincome() + "游戏币", 0, 1, "The operation of present coins has been operated for the member which ID is " + user.getUsername() + " ,a total of " + user.getUnincome() + " coins");
                adminLogServiceDao.addAdminLog(adminLog);
                userAwardServiceDao.save(ua);
            }
            result.put("success", Boolean.TRUE);
        } catch (Exception e) {
            result.put("success", Boolean.FALSE);
            result.put("message", "更新异常");
        }
        return result;
    }

}
